graphrag-search 0.2.11

GraphRAG — Hybrid search engine: vector embeddings + knowledge graph over Markdown notes. 100% local, single Rust binary.
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
use anyhow::{Context, Result};
use indicatif::{ProgressBar, ProgressStyle};
use log::{debug, info};
use rusqlite::Connection;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use walkdir::WalkDir;

use crate::chunking::{chunk_document, parse_frontmatter, slugify};
use crate::db::keys::{node_key, note_key};
use crate::db::schema;
use crate::embed::ollama::OllamaClient;
use crate::ner::{extract_entities_batch, Entity, DEFAULT_LABELS};
use crate::vector;

/// Datos de un chunk ya embedido listo para almacenar
struct ChunkData {
    header: String,
    text: String,
    slug: String,
    embedding_blob: Vec<u8>,
}

/// Estadísticas de la construcción del grafo
#[derive(Debug, Default, Clone)]
pub struct BuildStats {
    pub files: usize,
    pub entities: usize,
    pub total_nodes: i64,
    pub total_edges: i64,
}

impl std::fmt::Display for BuildStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "📊 Resumen del grafo:\n\
             ├── Archivos procesados: {}\n\
             ├── Entidades extraídas: {}\n\
             ├── Total nodos:        {}\n\
             └── Total aristas:      {}",
            self.files, self.entities, self.total_nodes, self.total_edges
        )
    }
}

/// Resultado del procesamiento de un archivo, enviado del worker al writer
struct FileResult {
    relative_str: String,
    note_title: String,
    note_metadata: String,
    batch_entities: Vec<Vec<Entity>>,
    chunk_data: Vec<ChunkData>,
    parent_dir: String,
    tags: Vec<String>,
}

/// Load existing note hashes from the database.
///
/// Returns a map of relative path → (sha256 hash, node_id) for all existing
/// note nodes that have both `hash` and `path` fields in their JSON metadata.
/// Notes without these fields (e.g., from an older graphrag version) are
/// silently excluded — they will be reprocessed and updated with the fields
/// on the next build.
pub fn collect_existing_hashes(conn: &Connection) -> Result<HashMap<String, (String, i64)>> {
    // Mapa: ruta_relativa → (hash, id_del_nodo)
    let mut existing: HashMap<String, (String, i64)> = HashMap::new();
    let mut stmt = conn.prepare("SELECT id, label, metadata FROM nodes WHERE type = 'note'")?;
    let rows = stmt.query_map([], |row| {
        let id: i64 = row.get(0)?;
        let label: String = row.get(1)?;
        let meta_str: String = row.get::<_, Option<String>>(2)?.unwrap_or_default();
        Ok((id, label, meta_str))
    })?;

    for row in rows {
        let (id, _label, meta_str) = row?;
        if let Ok(meta) = serde_json::from_str::<serde_json::Value>(&meta_str) {
            if let Some(hash) = meta.get("hash").and_then(|h| h.as_str()) {
                if let Some(path) = meta.get("path").and_then(|p| p.as_str()) {
                    existing.insert(path.to_string(), (hash.to_string(), id));
                }
            }
        }
    }

    Ok(existing)
}

/// Construye un grafo de conocimiento desde un directorio de notas Markdown.
///
/// # Flujo
///
/// 1. Escanea recursivamente el directorio en busca de archivos `*.md`.
/// 2. Pre-examina cada archivo: calcula hash SHA256 y salta los no modificados.
/// 3. Procesa los archivos nuevos/modificados en PARALELO usando `std::thread::scope`.
///    Cada hilo abre su propia conexión SQLite.
/// 4. Para cada archivo: parsea frontmatter, trocea por cabeceras, extrae
///    entidades vía `extract_entities_batch` (una sola llamada a Ollama por archivo),
///    calcula relaciones de co-ocurrencia, e inserta todo.
/// 5. También extrae relaciones estructurales (directorio contenedor, tags del frontmatter).
/// 6. Tras todos los hilos, el hilo principal limpia notas eliminadas, entidades
///    huérfanas y repuebla el índice FTS5.
///
/// # Argumentos
///
/// * `repo_path` — Ruta al directorio raíz con las notas `.md`.
/// * `db_path` — Ruta al archivo SQLite de salida.
/// * `ollama_url` — URL del servidor Ollama (ej. `http://localhost:11434`).
/// * `ner_model` — Nombre del modelo Ollama para extracción de entidades.
/// * `embed_model` — Nombre del modelo Ollama para embeddings (reservado).
///
/// # Errores
///
/// Devuelve `anyhow::Error` si el directorio no existe, no contiene archivos
/// `.md`, o falla alguna operación de E/S o de base de datos.
pub fn build_graph(
    repo_path: &str,
    db_path: &str,
    ollama_url: &str,
    ner_model: &str,
    embed_model: &str,
    num_threads: usize,
) -> Result<BuildStats> {
    let repo = Path::new(repo_path);
    if !repo.is_dir() {
        anyhow::bail!("'{}' no es un directorio válido", repo_path);
    }

    // ── Inicializar base de datos ──────────────────────────────────────────
    // Si la BD venía de WAL mode (versiones anteriores), la transición a
    // DELETE la gestiona SQLite de forma segura (checkpoint automático al
    // cambiar `PRAGMA journal_mode`). NO borrar los ficheros `-wal`/`-shm`
    // a mano: hacerlo puede perder datos ya confirmados.
    let conn = Connection::open(db_path)
        .with_context(|| format!("No se pudo abrir base de datos: {}", db_path))?;
    schema::init_db(&conn)?;

    conn.execute_batch(
        "PRAGMA synchronous=NORMAL;
         PRAGMA cache_size=-64000;",
    )?;

    // Verificar que el journal mode es DELETE
    if let Ok(mode) = conn.query_row::<String, _, _>("PRAGMA journal_mode", [], |r| r.get(0)) {
        log::debug!("Main connection journal_mode: {}", mode);
        if mode.to_lowercase() != "delete" {
            log::warn!("Journal mode es '{}', no 'delete'. Forzando...", mode);
            let _ = conn.execute_batch("PRAGMA journal_mode=DELETE;");
        }
    }

    // ── Instalar manejador SIGINT (Ctrl+C) ─────────────────────────────
    // Dos etapas:
    //   1ª Ctrl+C: flag de interrupción → writer checkea flag, corta
    //   2ª Ctrl+C: exit inmediato (workers en llamadas Ollama lentas)
    let interrupted = Arc::new(AtomicBool::new(false));
    let sigint_flag = interrupted.clone();
    let second_signal = Arc::new(AtomicBool::new(false));
    let second_flag = second_signal.clone();
    if let Err(e) = ctrlc::set_handler(move || {
        if second_flag.load(Ordering::SeqCst) {
            // Segundo Ctrl+C: avisar que ya estamos parando
            eprintln!("⚠️  Ya estamos terminando. Espera a que los workers acaben su NER actual.");
            return;
        }
        // Primer Ctrl+C: flag para shutdown graceful
        sigint_flag.store(true, Ordering::SeqCst);
        eprintln!("\n⚠️  Recibida señal de interrupción. Terminando archivo actual...");
        eprintln!("⚠️  Presiona Ctrl+C de nuevo para ver este mensaje.");
        second_flag.store(true, Ordering::SeqCst);
    }) {
        log::warn!("No se pudo instalar manejador SIGINT: {}", e);
    }

    // ── Cargar hashes existentes de la BD ────────────────────────────────
    let existing = collect_existing_hashes(&conn)?;

    let total_files = existing.len();
    info!("Notas existentes en BD: {}", total_files);

    // ── Escanear archivos .md en disco ────────────────────────────────────
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.green} {msg}")
            .unwrap(),
    );
    spinner.set_message("🔍 Escaneando archivos .md...");

    let md_files: Vec<_> = WalkDir::new(repo)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
        .collect();

    spinner.finish_with_message(format!("✅ Encontrados {} archivos .md", md_files.len()));

    let total = md_files.len();
    info!("Encontrados {} archivos .md en {}", total, repo_path);
    debug!("Walkdir completado. Archivos .md encontrados: {}", total);

    if total == 0 {
        anyhow::bail!("No se encontraron archivos .md en {}", repo_path);
    }

    // ── Pre-examen: identificar archivos nuevos o modificados ──────────────
    let pre_spinner = ProgressBar::new_spinner();
    pre_spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.yellow} {msg}")
            .unwrap(),
    );
    pre_spinner.set_message(format!("🔍 Comparando hashes: 0/{}", total));
    let mut examined: usize = 0;
    let mut to_process: Vec<&Path> = Vec::new();
    for entry in &md_files {
        let md_path = entry.path();
        let relative = md_path.strip_prefix(repo).unwrap_or(md_path);
        let relative_str = relative.display().to_string();

        let text = match std::fs::read_to_string(md_path) {
            Ok(t) => t,
            Err(_) => {
                examined += 1;
                pre_spinner.set_message(format!("🔍 Comparando hashes: {}/{}", examined, total));
                continue;
            }
        };

        let mut hasher = Sha256::new();
        hasher.update(text.as_bytes());
        let result = hasher.finalize();
        let file_hash = result
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>();

        if let Some((stored_hash, _)) = existing.get(&relative_str) {
            if *stored_hash == file_hash {
                debug!("Archivo sin cambios, saltando: {}", relative_str);
                examined += 1;
                pre_spinner.set_message(format!("🔍 Comparando hashes: {}/{}", examined, total));
                continue;
            }
        }

        examined += 1;
        pre_spinner.set_message(format!("🔍 Comparando hashes: {}/{}", examined, total));
        to_process.push(md_path);
    }

    let total_to_process = to_process.len();
    info!(
        "Archivos a procesar (nuevos/modificados): {}",
        total_to_process
    );

    pre_spinner.finish_with_message(format!(
        "✅ Pre-examen completado: {} archivos a procesar",
        total_to_process
    ));

    // ── Barra de progreso principal ──────────────────────────────────────
    let pb = Mutex::new(ProgressBar::new(total_to_process as u64));
    pb.lock().unwrap().set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} {msg} ({per_sec:.yellow}, ETA: {eta})")
            .unwrap()
            .progress_chars("━╸━"),
    );

    // ── Procesamiento paralelo ────────────────────────────────────────────
    // Workers: leen archivos, parsean frontmatter, chunk, llaman a Ollama.
    // Writer: una sola conexión SQLite, escritura serializada vía canal.

    // Determinar número de hilos (de la configuración, con límite sensato)
    let num_threads = num_threads.clamp(1, 16);

    info!(
        "Procesando con {} hilos en paralelo (NER) + 1 escritor",
        num_threads
    );

    let chunk_size = total_to_process.div_ceil(num_threads);
    let chunks: Vec<&[&Path]> = to_process.chunks(chunk_size.max(1)).collect();

    // Canal para enviar datos de hilos → writer
    let (tx, rx) = mpsc::channel::<FileResult>();

    // Rebinding como referencias: move capturará copias (las referencias son Copy)
    let stats_lock = Mutex::new(BuildStats::default());
    let pb = &pb;
    let stats_lock = &stats_lock;
    let existing = &existing;
    let db_path = &db_path;
    let ollama_url = &ollama_url;
    let ner_model = &ner_model;
    let embed_model = &embed_model;

    // Directorios a saltar para relaciones estructurales
    let skip_dirs = ["notas", "muestra"];
    let interrupted = &interrupted;

    std::thread::scope(|s| {
        // ── Writer thread ──────────────────────────────────────────────
        // Una sola conexión, escritura serializada
        let _writer_handle = s.spawn(|| {
            let conn = match Connection::open(db_path) {
                Ok(c) => c,
                Err(e) => {
                    log::error!("Error abriendo conexión writer: {}", e);
                    return;
                }
            };
            // NO llamamos a schema::init_db — la conexión principal ya creó
            // las tablas. Solo configuramos PRAGMAs.
            conn.execute_batch(
                "PRAGMA journal_mode=DELETE;
                 PRAGMA synchronous=NORMAL;
                 PRAGMA cache_size=-64000;",
            ).ok();
            // Verificar que el journal mode es DELETE
            if let Ok(mode) = conn.query_row::<String, _, _>(
                "PRAGMA journal_mode", [], |r| r.get(0),
            ) {
                log::debug!("Writer journal_mode: {}", mode);
            }

            for result in rx {
                let FileResult {
                    relative_str,
                    note_title,
                    note_metadata,
                    batch_entities,
                    ref chunk_data,
                    parent_dir,
                    tags,
                } = result;

                // Transacción por archivo
                let tx = match conn.unchecked_transaction() {
                    Ok(t) => t,
                    Err(e) => {
                        log::error!("Error iniciando transacción writer para {}: {}", relative_str, e);
                        pb.lock().unwrap().inc(1);
                        continue;
                    }
                };

                // Si el archivo YA existía, limpiar sus aristas viejas
                // (lo hacemos por path en el metadata del nodo tipo 'note')
                // Buscamos el nodo anterior por path para borrar sus edges
                if let Some((_, old_id)) = existing.iter().find_map(|(p, v)| {
                    if *p == relative_str { Some(v) } else { None }
                }) {
                    if let Err(e) = tx.execute(
                        "DELETE FROM edges WHERE (target_id = ?1 AND type = 'mentioned_in') OR (source_id = ?1 AND type IN ('tagged_with', 'belongs_to', 'co_occurs_with', 'mentioned_in'))",
                        rusqlite::params![old_id],
                    ) {
                        log::warn!("⚠️  Error limpiando edges viejos para {}: {}", relative_str, e);
                    }
                    if let Err(e) = tx.execute(
                        "DELETE FROM edges WHERE target_id = ?1 OR source_id = ?1",
                        rusqlite::params![old_id],
                    ) {
                        log::warn!("⚠️  Error limpiando edges viejos (2) para {}: {}", relative_str, e);
                    }
                }

                // Insertar/actualizar nodo nota por `key` (identidad = ruta)
                if let Err(e) = tx.execute(
                    "INSERT INTO nodes (key, label, type, metadata, embedding)
                     VALUES (?1, ?2, 'note', ?3, ?4)
                     ON CONFLICT(key) DO UPDATE SET
                       label = excluded.label,
                       metadata = excluded.metadata,
                       embedding = excluded.embedding",
                    rusqlite::params![
                        note_key(&relative_str),
                        note_title,
                        note_metadata,
                        None::<&[u8]>
                    ],
                ) {
                    log::warn!("⚠️  Error insertando nodo nota '{}': {}", note_title, e);
                    pb.lock().unwrap().inc(1);
                    continue;
                }

                // Obtener ID de la nota
                let note_node_id: i64 = match tx.query_row(
                    "SELECT id FROM nodes WHERE key = ?1",
                    rusqlite::params![note_key(&relative_str)],
                    |row| row.get(0),
                ) {
                    Ok(id) => id,
                    Err(e) => {
                        log::warn!("⚠️  Error obteniendo node_id para '{}': {}", note_title, e);
                        pb.lock().unwrap().inc(1);
                        continue;
                    }
                };

                // Insertar entidades y aristas por cada chunk
                let mut all_entity_count: usize = 0;

                for (chunk_idx, entities) in batch_entities.iter().enumerate() {
                    let chunk_ref = if chunk_idx < chunk_data.len() && !chunk_data[chunk_idx].header.is_empty() {
                        format!("{}#{}", relative_str, chunk_data[chunk_idx].header)
                    } else {
                        relative_str.clone()
                    };

                    if entities.is_empty() {
                        continue;
                    }

                    // Contar entidades para stats
                    all_entity_count += entities.len();

                    // Insertar nodos de entidades y aristas "mentioned_in"
                    for ent in entities {
                        let ent_metadata = serde_json::json!({
                            "score": ent.score,
                            "source": ner_model,
                        });

                        if let Err(e) = tx.execute(
                            "INSERT INTO nodes (key, label, type, metadata, embedding)
                             VALUES (?1, ?2, ?3, ?4, ?5)
                             ON CONFLICT(key) DO UPDATE SET
                               metadata = excluded.metadata,
                               embedding = excluded.embedding",
                            rusqlite::params![node_key(&ent.label), ent.label, ent.type_, ent_metadata.to_string(), None::<&[u8]>],
                        ) {
                            log::warn!("⚠️  Error insertando entidad '{}': {}", ent.label, e);
                        }

                        if let Ok(ent_node_id) = tx.query_row::<i64, _, _>(
                            "SELECT id FROM nodes WHERE key = ?1",
                            rusqlite::params![node_key(&ent.label)],
                            |row| row.get(0),
                        ) {
                            if let Err(e) = tx.execute(
                                "INSERT OR IGNORE INTO edges (source_id, target_id, type, weight, context)
                                 VALUES (?1, ?2, 'mentioned_in', ?3, ?4)",
                                rusqlite::params![ent_node_id, note_node_id, ent.score, chunk_ref],
                            ) {
                                log::warn!("⚠️  Error insertando edge mentioned_in: {}", e);
                            }
                        }
                    }

                    // Co-ocurrencias dentro del mismo chunk
                    for i in 0..entities.len() {
                        for j in (i + 1)..entities.len() {
                            if entities[i].id == entities[j].id { continue; }
                            let weight = entities[i].score.min(entities[j].score);

                            if let (Ok(src_id), Ok(dst_id)) = (
                                tx.query_row::<i64, _, _>("SELECT id FROM nodes WHERE key = ?1",
                                    rusqlite::params![node_key(&entities[i].label)], |row| row.get(0)),
                                tx.query_row::<i64, _, _>("SELECT id FROM nodes WHERE key = ?1",
                                    rusqlite::params![node_key(&entities[j].label)], |row| row.get(0)),
                            ) {
                                if let Err(e) = tx.execute(
                                    "INSERT OR IGNORE INTO edges (source_id, target_id, type, weight, context)
                                     VALUES (?1, ?2, 'co_occurs_with', ?3, ?4)",
                                    rusqlite::params![src_id, dst_id, weight, chunk_ref],
                                ) {
                                    log::warn!("⚠️  Error insertando edge co_occurs_with: {}", e);
                                }
                            }
                        }
                    }
                }

                // Relaciones estructurales: directorio
                if !parent_dir.is_empty() && !skip_dirs.contains(&parent_dir.as_str()) {
                    if let Err(e) = tx.execute(
                        "INSERT INTO nodes (key, label, type, embedding) VALUES (?1, ?2, 'tag', ?3) ON CONFLICT(key) DO UPDATE SET embedding = excluded.embedding",
                        rusqlite::params![node_key(&parent_dir), parent_dir, None::<&[u8]>],
                    ) {
                        log::warn!("⚠️  Error insertando tag directorio '{}': {}", parent_dir, e);
                    }
                    if let Ok(dir_id) = tx.query_row::<i64, _, _>(
                        "SELECT id FROM nodes WHERE key = ?1",
                        rusqlite::params![node_key(&parent_dir)],
                        |row| row.get(0),
                    ) {
                        if let Err(e) = tx.execute(
                            "INSERT OR IGNORE INTO edges (source_id, target_id, type, weight, context)
                             VALUES (?1, ?2, 'belongs_to', 1.0, ?3)",
                            rusqlite::params![note_node_id, dir_id, relative_str],
                        ) {
                            log::warn!("⚠️  Error insertando edge belongs_to: {}", e);
                        }
                    }
                }

                // Relaciones estructurales: tags
                for tag in &tags {
                    if let Err(e) = tx.execute(
                        "INSERT INTO nodes (key, label, type, embedding) VALUES (?1, ?2, 'tag', ?3) ON CONFLICT(key) DO UPDATE SET embedding = excluded.embedding",
                        rusqlite::params![node_key(tag), tag, None::<&[u8]>],
                    ) {
                        log::warn!("⚠️  Error insertando tag '{}': {}", tag, e);
                    }
                    if let Ok(tag_id) = tx.query_row::<i64, _, _>(
                        "SELECT id FROM nodes WHERE key = ?1",
                        rusqlite::params![node_key(tag)],
                        |row| row.get(0),
                    ) {
                        if let Err(e) = tx.execute(
                            "INSERT OR IGNORE INTO edges (source_id, target_id, type, weight, context)
                             VALUES (?1, ?2, 'tagged_with', 1.0, ?3)",
                            rusqlite::params![note_node_id, tag_id, relative_str],
                        ) {
                            log::warn!("⚠️  Error insertando edge tagged_with: {}", e);
                        }
                    }
                }

                // Insertar chunks embedidos en la tabla `chunks`
                for cd in chunk_data {
                    if let Err(e) = crate::db::chunks::insert_chunk(
                        &tx, note_node_id, &cd.header, &cd.text, &cd.slug,
                        Some(&cd.embedding_blob), None,
                    ) {
                        log::warn!("⚠️  Error insertando chunk '{}': {}", cd.header, e);
                    }
                }

                // Commit de la transacción del archivo
                log::info!("  ▶ Guardando '{}' en BD...", relative_str);
                if let Err(e) = tx.commit() {
                    log::error!("Error haciendo commit writer para {}: {}", relative_str, e);
                    pb.lock().unwrap().inc(1);
                    continue;
                }
                log::info!("  ✓ Guardado '{}' en BD", relative_str);
                // Checkpoint TRUNCATE en la MISMA conexión del writer:
                // garantiza que los datos se escriban al DB principal
                // antes de que el writer entregue el control.
                let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");

                // Actualizar estadísticas compartidas
                {
                    let mut stats = stats_lock.lock().unwrap();
                    stats.files += 1;
                    stats.entities += all_entity_count;
                }

                pb.lock().unwrap().inc(1);

                // Verificar SIGINT después de commit
                if interrupted.load(Ordering::SeqCst) {
                    info!("Build interrumpido. Cortando...");
                    break;
                }

                let msg = format!("{} ({} chunks, {} entidades)", relative_str, chunk_data.len(), all_entity_count);
                pb.lock().unwrap().set_message(msg);
                debug!("  Commit OK. Nota '{}' procesada.", note_title);
            }
        });

        // ── Worker threads ──────────────────────────────────────────────
        // Solo leen archivos y llaman a Ollama. NO abren conexión SQLite.
        for chunk in chunks {
            let tx = tx.clone();
            s.spawn(move || {
                for md_path in chunk {
                    // Verificar interrupción antes de procesar cada archivo
                    if interrupted.load(Ordering::SeqCst) {
                        break;
                    }
                    let relative = md_path.strip_prefix(repo).unwrap_or(md_path);
                    let relative_str = relative.display().to_string();

                    // Leer archivo y calcular hash
                    let text = match std::fs::read_to_string(md_path) {
                        Ok(t) => t,
                        Err(e) => {
                            log::warn!("⚠️  Error leyendo {}: {}", md_path.display(), e);
                            pb.lock().unwrap().inc(1);
                            continue;
                        }
                    };

                    let mut hasher = Sha256::new();
                    hasher.update(text.as_bytes());
                    let result = hasher.finalize();
                    let file_hash = result
                        .iter()
                        .map(|b| format!("{:02x}", b))
                        .collect::<String>();

                    let (metadata, body) = parse_frontmatter(&text);
                    debug!(
                        "Procesando archivo: {} (hash={})",
                        relative_str,
                        &file_hash[..8]
                    );

                    let note_stem = md_path.file_stem().unwrap().to_string_lossy();
                    if note_stem.is_empty() {
                        log::warn!("⚠️  Saltando archivo sin nombre: {}", md_path.display());
                        pb.lock().unwrap().inc(1);
                        continue;
                    }

                    let note_id_slug = slugify(&note_stem);
                    let note_title = metadata
                        .get("title")
                        .cloned()
                        .unwrap_or_else(|| note_stem.to_string());

                    let note_metadata = serde_json::json!({
                        "path": relative_str,
                        "slug": note_id_slug,
                        "hash": file_hash,
                        "content": body.trim(),
                    });

                    // Chunking + NER batch con reintentos
                    let chunks = chunk_document(&text);
                    debug!("  Chunks generados: {}", chunks.len());

                    let chunk_texts: Vec<&str> = chunks.iter().map(|c| c.text.as_str()).collect();
                    let labels = DEFAULT_LABELS;

                    // Reintentar NER hasta 3 veces con backoff
                    let batch_entities = {
                        let mut result = None;
                        for attempt in 1..=3 {
                            match extract_entities_batch(
                                ollama_url,
                                ner_model,
                                &chunk_texts,
                                labels,
                            ) {
                                Ok(ents) => {
                                    result = Some(ents);
                                    break;
                                }
                                Err(e) => {
                                    log::warn!(
                                        "⚠️  Error en NER batch [model={}] para {} (intento {}/3): {}",
                                        ner_model,
                                        relative_str,
                                        attempt,
                                        e
                                    );
                                    if attempt < 3 {
                                        let delay = Duration::from_secs(2u64.pow(attempt));
                                        std::thread::sleep(delay);
                                    }
                                }
                            }
                        }
                        match result {
                            Some(ents) => ents,
                            None => {
                                log::error!(
                                    "❌ NER falló tras 3 intentos para {}. Saltando archivo.",
                                    relative_str
                                );
                                pb.lock().unwrap().inc(1);
                                continue;
                            }
                        }
                    };

                    // Verificar interrupción después de NER
                    if interrupted.load(Ordering::SeqCst) {
                        break;
                    }

                    // Tags del frontmatter
                    let tags: Vec<String> = metadata
                        .get("tags")
                        .map(|t| {
                            t.split(',')
                                .map(|s| s.trim().to_string())
                                .filter(|s| !s.is_empty())
                                .collect()
                        })
                        .unwrap_or_default();

                    // Directorio padre
                    let parent_dir = md_path
                        .parent()
                        .and_then(|p| p.file_name())
                        .map(|p| p.to_string_lossy().to_string())
                        .unwrap_or_default();

                    // Batch embed chunks via Ollama
                    let chunk_data: Vec<ChunkData> = {
                        if chunks.is_empty() {
                            Vec::new()
                        } else {
                            let embed_texts: Vec<String> = chunks
                                .iter()
                                .map(|c| format!("{}\n{}", c.header, c.text))
                                .collect();
                            let embed_refs: Vec<&str> =
                                embed_texts.iter().map(|s| s.as_str()).collect();

                            let ollama = OllamaClient::new(ollama_url, embed_model);
                            match ollama.batch_embed(&embed_refs) {
                                Ok(embs) => chunks
                                    .iter()
                                    .zip(embs.iter())
                                    .map(|(chunk, emb)| {
                                        let slug =
                                            slugify(&chunk.text.chars().take(80).collect::<String>());
                                        ChunkData {
                                            header: chunk.header.clone(),
                                            text: chunk.text.clone(),
                                            slug,
                                            embedding_blob: vector::vector_to_blob(emb),
                                        }
                                    })
                                    .collect(),
                                Err(e) => {
                                    log::warn!(
                                        "⚠️  Ollama embedding failed for {} (model '{}' at {}): {}. \
                                         File processed without chunk embeddings — vector search \
                                         for this file's content will not work until embeddings \
                                         are available.",
                                        relative_str,
                                        embed_model,
                                        ollama_url,
                                        e
                                    );
                                    Vec::new()
                                }
                            }
                        }
                    };

                    // Verificar interrupción después de embeddings
                    if interrupted.load(Ordering::SeqCst) {
                        break;
                    }

                    // Enviar al writer
                    let result = FileResult {
                        relative_str: relative_str.to_string(),
                        note_title,
                        note_metadata: note_metadata.to_string(),
                        batch_entities,
                        chunk_data,
                        parent_dir,
                        tags,
                    };

                    if let Err(e) = tx.send(result) {
                        log::error!("Error enviando resultado al writer: {}", e);
                    }
                }
            });
        }

        // Drop del tx original para que el writer termine cuando todos los workers acaben
        drop(tx);
    });

    // ── Recolectar stats de los hilos ─────────────────────────────────────
    let thread_stats = stats_lock.lock().unwrap().clone();

    // ── Verificar interrupción por SIGINT ─────────────────────────────────
    if interrupted.load(Ordering::SeqCst) {
        pb.lock()
            .unwrap()
            .finish_with_message("⚠️ Build interrumpido por el usuario");
        eprintln!(
            "⚠️  Build interrumpido. {} archivos procesados. Continuando cierre limpio...",
            thread_stats.files
        );
        // NO llamamos a process::exit(130) aquí, dejamos que el conexión
        // se cierre limpiamente.
        // El writer ya hizo TRUNCATE checkpoint antes de romper el loop,
        // los datos están en el DB principal.
        let mut stats = thread_stats;
        // Consultar estadísticas reales de la BD antes de salir
        stats.total_nodes = conn
            .query_row("SELECT COUNT(*) FROM nodes", [], |r| r.get(0))
            .unwrap_or(0);
        stats.total_edges = conn
            .query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))
            .unwrap_or(0);
        return Ok(stats);
    }

    // ── Limpiar notas eliminadas del disco ────────────────────────────────
    let prune_spinner = ProgressBar::new_spinner();
    prune_spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.red} {msg}")
            .unwrap(),
    );
    prune_spinner.set_message("🧹 Limpiando notas eliminadas...");

    let ids_to_prune: Vec<(i64, String)> = {
        let mut stmt = conn.prepare("SELECT id, metadata FROM nodes WHERE type = 'note'")?;
        let rows = stmt.query_map([], |row| {
            let id: i64 = row.get(0)?;
            let meta_str: String = row.get::<_, Option<String>>(1)?.unwrap_or_default();
            Ok((id, meta_str))
        })?;

        let mut to_remove = Vec::new();
        for row in rows {
            let (id, meta_str) = row?;
            if let Ok(meta) = serde_json::from_str::<serde_json::Value>(&meta_str) {
                let should_keep = meta
                    .get("path")
                    .and_then(|p| p.as_str())
                    .map(|p| {
                        let full_path = repo.join(p);
                        full_path.exists()
                    })
                    .unwrap_or(false);

                if !should_keep {
                    let note_label = meta
                        .get("slug")
                        .and_then(|s| s.as_str())
                        .unwrap_or("unknown")
                        .to_string();
                    to_remove.push((id, note_label));
                }
            }
        }
        to_remove
    };

    let pruned = ids_to_prune.len();
    if pruned > 0 {
        prune_stale_notes(&conn, &ids_to_prune)?;
    }
    prune_spinner.finish_with_message(format!("✅ {} notas eliminadas del disco", pruned));

    // ── Limpiar entidades huérfanas ──────────────────────────────────────
    // Nodos que no son notas y no tienen ninguna arista → se eliminan.
    delete_orphan_entities(&conn)?;

    pb.lock().unwrap().finish_with_message("✅ ¡Completado!");

    // ── Repoblar índice FTS5 ──────────────────────────────────────────────
    let fts_spinner = ProgressBar::new_spinner();
    fts_spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.blue} {msg}")
            .unwrap(),
    );
    fts_spinner.set_message("📑 Repoblando índice FTS5...");

    conn.execute_batch(
        "DELETE FROM notes_fts;
         INSERT INTO notes_fts(rowid, title, content)
         SELECT id, label, COALESCE(json_extract(metadata, '$.content'), '')
         FROM nodes
         WHERE COALESCE(json_extract(metadata, '$.content'), '') != '';",
    )?;

    fts_spinner.finish_with_message("✅ Índice FTS5 repoblado");

    // ── Estadísticas finales ──────────────────────────────────────────────
    let mut stats = thread_stats;
    stats.total_nodes = conn.query_row("SELECT COUNT(*) FROM nodes", [], |r| r.get(0))?;
    stats.total_edges = conn.query_row("SELECT COUNT(*) FROM edges", [], |r| r.get(0))?;

    debug!("Índice FTS5 repoblado desde {} nodos.", stats.total_nodes);
    info!("Grafo construido: {}", stats);

    Ok(stats)
}

/// Delete every entity-like node that is not referenced by any edge.
///
/// The `type NOT IN ('note', 'root', 'system')` predicate covers the remaining
/// entity-like node types (entity, tag, language, tool, …) without a hardcoded,
/// easily-diverging allow-list, while preserving the bootstrap nodes
/// (`_root`, `_graphrag_core`, `_unresolved`) that carry the `root`/`system`
/// types and may legitimately have no edges. Errors are propagated to the caller.
pub fn delete_orphan_entities(conn: &rusqlite::Connection) -> anyhow::Result<()> {
    conn.execute(
        "DELETE FROM nodes WHERE type NOT IN ('note', 'root', 'system')
         AND id NOT IN (SELECT source_id FROM edges UNION SELECT target_id FROM edges);",
        [],
    )
    .context("Error deleting orphan entity nodes")?;
    Ok(())
}

/// Delete stale notes (whose files no longer exist on disk) and their associated data.
/// Returns the number of pruned notes.
pub fn prune_stale_notes(
    conn: &rusqlite::Connection,
    ids_to_prune: &[(i64, String)],
) -> anyhow::Result<usize> {
    let pruned = ids_to_prune.len();
    if pruned > 0 {
        for (id, label) in ids_to_prune {
            conn.execute(
                "DELETE FROM edges WHERE source_id = ?1 OR target_id = ?1",
                rusqlite::params![id],
            )
            .with_context(|| format!("Error deleting edges for pruned note id={}", id))?;

            // Delete chunks referencing this note before deleting the node
            // to avoid FOREIGN KEY constraint failure.
            conn.execute(
                "DELETE FROM chunks WHERE note_id = ?1",
                rusqlite::params![id],
            )
            .with_context(|| format!("Error deleting chunks for pruned note id={}", id))?;

            conn.execute("DELETE FROM nodes WHERE id = ?1", rusqlite::params![id])
                .with_context(|| format!("Error deleting node id={} label={}", id, label))?;

            info!("Nota eliminada (archivo no encontrado): {}", label);
        }
        info!("Notas eliminadas del grafo: {}", pruned);
        debug!(
            "Limpieza completada: {} notas eliminadas del disco.",
            pruned
        );
    }

    Ok(pruned)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json;
    use std::fs;
    use tempfile::NamedTempFile;

    /// Crea un directorio temporal con algunos archivos .md para pruebas
    /// de integración.
    fn setup_test_repo() -> (tempfile::TempDir, NamedTempFile) {
        let dir = tempfile::tempdir().expect("crear tempdir");
        let db = NamedTempFile::new().expect("crear db temporal");

        // Escribir un par de notas de prueba
        fs::write(
            dir.path().join("hola.md"),
            "---\ntitle: Hola Mundo\ntags: prueba, rust\n---\n\n# Introducción\n\nEsto es una nota de prueba.\n\n# Contenido\n\nPython es un lenguaje. Rust es otro lenguaje.\n",
        )
        .expect("escribir hola.md");

        fs::write(
            dir.path().join("subdir").join("otra.md"),
            "---\ntitle: Otra Nota\ntags: ejemplo\n---\n\n# Sección\n\nPython y Rust son lenguajes de programación.\n",
        )
        .expect("escribir otra.md");

        // Crear subdirectorio
        fs::create_dir_all(dir.path().join("subdir")).expect("crear subdir");

        (dir, db)
    }

    #[test]
    fn test_build_graph_empty_dir() {
        let dir = tempfile::tempdir().expect("crear tempdir");
        let db = NamedTempFile::new().expect("crear db temporal");

        // Directorio sin .md debe fallar
        let result = build_graph(
            dir.path().to_str().unwrap(),
            db.path().to_str().unwrap(),
            "http://localhost:11434",
            "test-model",
            "test-embed",
            4,
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("No se encontraron archivos .md"),
            "error: {}",
            err
        );
    }

    #[test]
    fn test_build_graph_invalid_repo() {
        let db = NamedTempFile::new().expect("crear db temporal");
        let result = build_graph(
            "/ruta/que/no/existe",
            db.path().to_str().unwrap(),
            "http://localhost:11434",
            "test-model",
            "test-embed",
            4,
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("no es un directorio válido"), "error: {}", err);
    }

    // Prueba de integración que verifica que el pipeline no crashea
    // (aunque fallará en extract_entities porque no hay Ollama).
    // Util para depurar el flujo hasta NER.
    #[test]
    #[ignore = "needs Ollama running"]
    fn test_build_graph_pipeline_structure() {
        let (_dir, _db) = setup_test_repo();
        // Esta prueba fallará por no tener Ollama, pero verifica que
        // el resto del pipeline (lectura, chunking, schema SQL) funciona.
        let result = build_graph(
            _dir.path().to_str().unwrap(),
            _db.path().to_str().unwrap(),
            "http://localhost:11434",
            "test-model",
            "test-embed",
            4,
        );
        // Esperamos un error de conexión a Ollama, NO un error de
        // schema, directorio, o SQL.
        if let Err(e) = &result {
            let msg = e.to_string();
            // No debe ser "no es un directorio" ni "no se encontraron"
            assert!(
                !msg.contains("no es un directorio"),
                "fallo temprano inesperado: {}",
                msg
            );
            assert!(
                !msg.contains("No se encontraron"),
                "fallo temprano inesperado: {}",
                msg
            );
        }
    }

    #[test]
    fn test_prune_stale_notes_fk_failure() {
        // Set up in-memory DB with schema (includes PRAGMA foreign_keys=ON)
        let conn = Connection::open_in_memory().unwrap();
        schema::init_db(&conn).unwrap();

        // Insert a note node
        conn.execute(
            "INSERT INTO nodes (id, key, label, type, metadata) VALUES (?1, ?2, ?3, 'note', ?4)",
            rusqlite::params![
                100,
                crate::db::keys::note_key("test-note"),
                "test-note",
                r#"{"path":"not/exists.md","slug":"test-note"}"#
            ],
        )
        .unwrap();

        // Insert 2 chunk rows referencing note_id=100
        conn.execute(
            "INSERT INTO chunks (note_id, header, text, slug) VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![100, "Intro", "Test content one", "intro"],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO chunks (note_id, header, text, slug) VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![100, "Details", "Test content two", "details"],
        )
        .unwrap();

        // Insert an edge referencing node_id=100
        conn.execute(
            "INSERT INTO edges (source_id, target_id, type, weight) VALUES (?1, ?2, 'test', 1.0)",
            rusqlite::params![100, 100],
        )
        .unwrap();

        // Call prune_stale_notes — should SUCCEED now because the fix deletes chunks first
        let result = prune_stale_notes(&conn, &[(100, "test-note".into())]);
        assert!(
            result.is_ok(),
            "GREEN: Expected success after fix — with DELETE FROM chunks before node deletion, \
             the FK constraint should not be violated. Got error: {:?}",
            result
        );

        // Verify the note node, its chunks, and its edges are all gone
        let note_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE id = 100", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(note_count, 0, "note node should be deleted");

        let chunk_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM chunks WHERE note_id = 100", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(chunk_count, 0, "chunks should be deleted");

        let edge_count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges WHERE source_id = 100 OR target_id = 100",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(edge_count, 0, "edges should be deleted");
    }

    #[test]
    fn test_delete_orphan_entities_removes_orphan_keeps_connected() {
        let conn = Connection::open_in_memory().unwrap();
        schema::init_db(&conn).unwrap();

        // A note acting as the anchor of the connected entity.
        conn.execute(
            "INSERT INTO nodes (id, key, label, type, metadata) VALUES (?1, ?2, ?3, 'note', '{}')",
            rusqlite::params![200, crate::db::keys::note_key("anchor"), "anchor"],
        )
        .unwrap();

        // Entity with NO edges → must be pruned.
        conn.execute(
            "INSERT INTO nodes (id, key, label, type, metadata) VALUES (?1, ?2, ?3, 'language', '{}')",
            rusqlite::params![201, "ent-orphan", "Orphan"],
        )
        .unwrap();

        // Bootstrap `system` node with NO edges → must be preserved.
        conn.execute(
            "INSERT INTO nodes (id, key, label, type, metadata) VALUES (?1, ?2, ?3, 'system', '{}')",
            rusqlite::params![203, "_graphrag_core", "_graphrag_core"],
        )
        .unwrap();

        // Bootstrap `root` node with NO edges → must be preserved.
        conn.execute(
            "INSERT INTO nodes (id, key, label, type, metadata) VALUES (?1, ?2, ?3, 'root', '{}')",
            rusqlite::params![204, "_root", "_root"],
        )
        .unwrap();

        // Entity WITH an edge → must survive.
        conn.execute(
            "INSERT INTO nodes (id, key, label, type, metadata) VALUES (?1, ?2, ?3, 'tool', '{}')",
            rusqlite::params![202, "ent-kept", "Kept"],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO edges (source_id, target_id, type, weight) VALUES (?1, ?2, 'mentioned_in', 1.0)",
            rusqlite::params![202, 200],
        )
        .unwrap();

        delete_orphan_entities(&conn).expect("orphan cleanup should succeed");

        let orphan: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE id = 201", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(orphan, 0, "orphan entity (no edges) should be deleted");

        let kept: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE id = 202", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(kept, 1, "entity with edges should remain");

        let note: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE id = 200", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(note, 1, "note nodes must never be pruned here");

        let system: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE id = 203", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(
            system, 1,
            "orphan `system` bootstrap node must be preserved"
        );

        let root: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE id = 204", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(root, 1, "orphan `root` bootstrap node must be preserved");
    }

    #[test]
    fn test_build_stats_display() {
        let stats = BuildStats {
            files: 10,
            entities: 42,
            total_nodes: 100,
            total_edges: 250,
        };
        let output = stats.to_string();
        assert!(output.contains("10"));
        assert!(output.contains("42"));
        assert!(output.contains("100"));
        assert!(output.contains("250"));
        assert!(output.contains("Archivos procesados"));
    }

    // ── Tests for collect_existing_hashes ──────────────────────────────

    #[test]
    fn test_collect_existing_hashes_includes_matching() {
        let conn = Connection::open_in_memory().unwrap();
        crate::db::schema::init_db(&conn).unwrap();

        // Insert a note node with hash + path in metadata
        conn.execute(
            "INSERT INTO nodes (key, label, type, metadata) VALUES (?1, ?2, 'note', ?3)",
            rusqlite::params![
                crate::db::keys::note_key("test-note"),
                "test-note",
                r#"{"path": "docs/guide.md", "hash": "abc123def456", "content": "hello"}"#
            ],
        )
        .unwrap();

        let result = collect_existing_hashes(&conn).unwrap();

        assert_eq!(result.len(), 1, "should contain exactly one entry");
        let (hash, _id) = result
            .get("docs/guide.md")
            .expect("should contain key 'docs/guide.md'");
        assert_eq!(hash, "abc123def456", "hash should match");
    }

    #[test]
    fn test_collect_existing_hashes_excludes_legacy() {
        let conn = Connection::open_in_memory().unwrap();
        crate::db::schema::init_db(&conn).unwrap();

        // Insert a note node with metadata lacking hash and path (legacy format)
        conn.execute(
            "INSERT INTO nodes (key, label, type, metadata) VALUES (?1, ?2, 'note', ?3)",
            rusqlite::params![
                crate::db::keys::note_key("legacy-note"),
                "legacy-note",
                r#"{"slug": "foo", "content": "bar"}"#
            ],
        )
        .unwrap();

        let result = collect_existing_hashes(&conn).unwrap();

        assert!(
            result.is_empty(),
            "legacy note without hash/path should be excluded"
        );
    }

    #[test]
    fn test_wal_checkpoint_preserves_committed_data() -> anyhow::Result<()> {
        let dir = tempfile::tempdir()?;
        let db_path = dir.path().join("test.db");
        let db_str = db_path.to_str().unwrap();

        // Connection 1: writer with WAL mode
        let conn1 = Connection::open(db_str)?;
        conn1.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")?;
        crate::db::schema::init_db(&conn1)?;

        // Insert a note in a transaction and commit
        conn1.execute(
            "INSERT INTO nodes (key, label, type, metadata) VALUES ('node:test-note', 'test-note', 'note', '{\"hash\":\"abc\",\"path\":\"test.md\"}')",
            [],
        )?;

        // Simulate WAL checkpoint (as SIGINT handler would do)
        conn1.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
        drop(conn1);

        // Reopen and verify the data survives
        let conn2 = Connection::open(db_str)?;
        let count: i64 = conn2.query_row(
            "SELECT COUNT(*) FROM nodes WHERE label = 'test-note'",
            [],
            |r| r.get(0),
        )?;
        assert_eq!(count, 1, "Data should survive WAL checkpoint + reopen");
        Ok(())
    }

    #[test]
    fn test_incremental_build_roundtrip() -> anyhow::Result<()> {
        // Create a temp directory with 3 .md files
        let dir = tempfile::tempdir()?;
        let db_path = dir.path().join("test.db");
        let db_str = db_path.to_str().unwrap().to_string();
        let repo_path = dir.path().join("notes");
        std::fs::create_dir_all(&repo_path)?;

        // Write 3 .md files
        let note1_path = repo_path.join("alpha.md");
        std::fs::write(
            &note1_path,
            "---\ntitle: Alpha\n---\n# Alpha\n\nContent about Python.\n",
        )?;

        let note2_path = repo_path.join("beta.md");
        std::fs::write(
            &note2_path,
            "---\ntitle: Beta\n---\n# Beta\n\nContent about Rust.\n",
        )?;

        let note3_path = repo_path.join("gamma.md");
        std::fs::write(
            &note3_path,
            "---\ntitle: Gamma\n---\n# Gamma\n\nContent about Go.\n",
        )?;

        // Compute hashes for all 3 files
        let compute_hash = |path: &std::path::Path| -> String {
            let text = std::fs::read_to_string(path).unwrap();
            let mut hasher = Sha256::new();
            hasher.update(text.as_bytes());
            let result = hasher.finalize();
            result
                .iter()
                .map(|b| format!("{:02x}", b))
                .collect::<String>()
        };

        let hash1 = compute_hash(&note1_path);
        let hash2 = compute_hash(&note2_path);
        let hash3 = compute_hash(&note3_path);

        // Step 1: Insert notes into DB as if they were already processed
        // (simulating the state after a first successful build)
        let conn = Connection::open(&db_str)?;
        schema::init_db(&conn)?;
        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")?;

        let rel1 = "alpha.md";
        let rel2 = "beta.md";
        let rel3 = "gamma.md";

        conn.execute(
            "INSERT INTO nodes (key, label, type, metadata) VALUES ('node:Alpha', 'Alpha', 'note', ?1)",
            rusqlite::params![serde_json::json!({
                "path": rel1,
                "hash": hash1,
                "slug": "alpha",
                "content": "# Alpha\n\nContent about Python."
            })
            .to_string()],
        )?;
        conn.execute(
            "INSERT INTO nodes (key, label, type, metadata) VALUES ('node:Beta', 'Beta', 'note', ?1)",
            rusqlite::params![serde_json::json!({
                "path": rel2,
                "hash": hash2,
                "slug": "beta",
                "content": "# Beta\n\nContent about Rust."
            })
            .to_string()],
        )?;
        conn.execute(
            "INSERT INTO nodes (key, label, type, metadata) VALUES ('node:Gamma', 'Gamma', 'note', ?1)",
            rusqlite::params![serde_json::json!({
                "path": rel3,
                "hash": hash3,
                "slug": "gamma",
                "content": "# Gamma\n\nContent about Go."
            })
            .to_string()],
        )?;

        drop(conn);

        // Step 2: Verify collect_existing_hashes finds all 3 notes
        {
            let conn = Connection::open(&db_str)?;
            let existing = collect_existing_hashes(&conn)?;
            assert_eq!(existing.len(), 3, "Should find all 3 notes with hash/path");
            assert!(existing.contains_key("alpha.md"));
            assert!(existing.contains_key("beta.md"));
            assert!(existing.contains_key("gamma.md"));
        }

        // Step 3: Verify hashes match (files unchanged)
        {
            let conn = Connection::open(&db_str)?;
            let existing = collect_existing_hashes(&conn)?;
            assert_eq!(existing.len(), 3, "Should still find 3 notes");

            assert_eq!(
                existing.get("alpha.md").unwrap().0,
                compute_hash(&note1_path),
                "Hash for alpha should match"
            );
            assert_eq!(
                existing.get("beta.md").unwrap().0,
                compute_hash(&note2_path),
                "Hash for beta should match"
            );
            assert_eq!(
                existing.get("gamma.md").unwrap().0,
                compute_hash(&note3_path),
                "Hash for gamma should match"
            );
        }

        // Step 4: Modify one file
        std::fs::write(
            &note1_path,
            "---\ntitle: Alpha\n---\n# Alpha\n\nModified content about Python and Rust.\n",
        )?;
        let new_hash1 = compute_hash(&note1_path);
        assert_ne!(
            new_hash1, hash1,
            "Hash should be different after modification"
        );

        // Step 5: After modification, stored hash should differ from new file hash
        {
            let conn = Connection::open(&db_str)?;
            let existing = collect_existing_hashes(&conn)?;
            assert_eq!(existing.len(), 3, "Should still find 3 notes in DB");

            let (stored_hash, _) = existing.get("alpha.md").unwrap();
            assert_ne!(
                *stored_hash, new_hash1,
                "Stored hash should differ from new file hash"
            );
            // Stored hash should still equal the ORIGINAL hash
            assert_eq!(
                *stored_hash, hash1,
                "Stored hash should equal original hash"
            );
        }

        Ok(())
    }

    // ── node-identity by key (RED) ─────────────────────────────────────

    /// Simulate two note upserts sharing a label but with distinct keys.
    /// They must produce two nodes (no collision on title).
    #[test]
    fn test_upsert_note_by_key_distinct_titles() {
        let conn = Connection::open_in_memory().unwrap();
        schema::init_db(&conn).unwrap();

        let upsert = |key: &str, label: &str| {
            conn.execute(
                "INSERT INTO nodes (key, label, type, metadata, embedding)
                 VALUES (?1, ?2, 'note', '{}', NULL)
                 ON CONFLICT(key) DO UPDATE SET
                   label = excluded.label,
                   metadata = excluded.metadata,
                   embedding = excluded.embedding",
                rusqlite::params![key, label],
            )
            .unwrap();
        };

        upsert("note:a/dup.md", "Duplicado");
        upsert("note:b/dup.md", "Duplicado");

        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM nodes WHERE label = 'Duplicado' AND type = 'note'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 2, "distinct keys must yield two note nodes");
    }

    /// End-to-end convergence: two files with the same title.
    /// Requires a running Ollama server.
    #[test]
    #[ignore = "needs Ollama"]
    fn test_build_duplicate_titles_converges() -> anyhow::Result<()> {
        let dir = tempfile::tempdir()?;
        let repo = dir.path().join("repo");
        fs::create_dir_all(repo.join("a"))?;
        fs::create_dir_all(repo.join("b"))?;
        fs::write(
            repo.join("a/dup.md"),
            "---\ntitle: Duplicado\n---\n# A\n\nContenido uno sobre Python y Docker.\n",
        )?;
        fs::write(
            repo.join("b/dup.md"),
            "---\ntitle: Duplicado\n---\n# B\n\nContenido dos sobre Rust y SQLite.\n",
        )?;

        let db_path = dir.path().join("test.db");
        let db_str = db_path.to_str().unwrap();
        let repo_str = repo.to_str().unwrap();

        let stats1 = build_graph(
            repo_str,
            db_str,
            "http://localhost:11434",
            "llama3.2:3b",
            "nomic-embed-text",
            2,
        )?;
        assert_eq!(stats1.files, 2, "first build must process 2 files");

        {
            let conn = Connection::open(db_str)?;
            let notes: i64 =
                conn.query_row("SELECT COUNT(*) FROM nodes WHERE type = 'note'", [], |r| {
                    r.get(0)
                })?;
            assert_eq!(notes, 2, "two distinct note nodes must exist");
        }

        let stats2 = build_graph(
            repo_str,
            db_str,
            "http://localhost:11434",
            "llama3.2:3b",
            "nomic-embed-text",
            2,
        )?;
        assert_eq!(
            stats2.files, 0,
            "second build must report 0 files to process"
        );

        Ok(())
    }
}