brainwires-cognition 0.8.0

Unified intelligence layer — knowledge graphs, adaptive prompting, RAG, spectral math, and code analysis for the Brainwires Agent Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
use super::*;
use tempfile::TempDir;

// Helper to create a test client
async fn create_test_client() -> (RagClient, TempDir) {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("db").to_string_lossy().to_string();
    let cache_path = temp_dir.path().join("cache.json");
    let client = RagClient::new_with_db_path(&db_path, cache_path)
        .await
        .unwrap();
    (client, temp_dir)
}

// ===== Client Initialization Tests =====

#[tokio::test]
async fn test_new_with_db_path() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("db").to_string_lossy().to_string();
    let cache_path = temp_dir.path().join("cache.json");

    let result = RagClient::new_with_db_path(&db_path, cache_path).await;
    assert!(result.is_ok());

    let client = result.unwrap();
    assert_eq!(client.embedding_dimension(), 384);
}

#[tokio::test]
async fn test_client_clone() {
    let (client, _temp_dir) = create_test_client().await;
    let _cloned = client.clone();
    // Should compile and not panic
}

#[tokio::test]
async fn test_config_accessor() {
    let (client, _temp_dir) = create_test_client().await;
    let config = client.config();
    assert!(config.indexing.chunk_size > 0);
}

#[tokio::test]
async fn test_embedding_dimension_accessor() {
    let (client, _temp_dir) = create_test_client().await;
    let dimension = client.embedding_dimension();
    assert_eq!(dimension, 384); // all-MiniLM-L6-v2 has 384 dimensions
}

// ===== normalize_path Tests =====

#[test]
fn test_normalize_path_valid() {
    let result = RagClient::normalize_path(".");
    assert!(result.is_ok());
    let normalized = result.unwrap();
    assert!(!normalized.is_empty());
}

#[test]
fn test_normalize_path_nonexistent() {
    let result = RagClient::normalize_path("/nonexistent/path/12345");
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Failed to canonicalize")
    );
}

#[test]
fn test_normalize_path_absolute() {
    let temp_dir = TempDir::new().unwrap();
    let path = temp_dir.path().to_string_lossy().to_string();

    let result = RagClient::normalize_path(&path);
    assert!(result.is_ok());
    let normalized = result.unwrap();
    assert!(normalized.starts_with('/'));
}

// ===== index_codebase Tests =====

#[tokio::test]
async fn test_index_codebase_empty_directory() {
    let (client, temp_dir) = create_test_client().await;
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();

    let request = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: None,
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };

    let result = client.index_codebase(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(response.files_indexed, 0);
}

#[tokio::test]
async fn test_index_codebase_with_single_file() {
    let (client, temp_dir) = create_test_client().await;
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn main() {}").unwrap();

    let request = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("test-project".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };

    let result = client.index_codebase(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(response.files_indexed, 1);
    assert!(response.chunks_created > 0);
    assert!(response.embeddings_generated > 0);
}

#[tokio::test]
async fn test_index_codebase_validation_failure() {
    let (client, _temp_dir) = create_test_client().await;

    let request = IndexRequest {
        path: "/nonexistent/path".to_string(),
        project: None,
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };

    let result = client.index_codebase(request).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("does not exist"));
}

// ===== query_codebase Tests =====

#[tokio::test]
async fn test_query_codebase_empty_index() {
    let (client, _temp_dir) = create_test_client().await;

    let request = QueryRequest {
        query: "test query".to_string(),
        path: None,
        project: None,
        limit: 10,
        min_score: 0.7,
        hybrid: true,
    };

    let result = client.query_codebase(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(response.results.len(), 0);
    assert_eq!(response.threshold_used, 0.7);
    assert!(!response.threshold_lowered);
}

#[tokio::test]
async fn test_query_codebase_with_data() {
    let (client, temp_dir) = create_test_client().await;

    // Index some data first
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(
        data_dir.join("test.rs"),
        "fn authenticate_user() { /* authentication logic */ }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("test-project".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Now query
    let query_req = QueryRequest {
        query: "authentication".to_string(),
        path: None,
        project: Some("test-project".to_string()),
        limit: 10,
        min_score: 0.3,
        hybrid: true,
    };

    let result = client.query_codebase(query_req).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert!(response.results.len() > 0);
    assert!(response.duration_ms > 0);
}

#[tokio::test]
async fn test_query_codebase_adaptive_threshold() {
    let (client, temp_dir) = create_test_client().await;

    // Index some data
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn hello() {}").unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: None,
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Query with high threshold (might trigger adaptive lowering)
    let query_req = QueryRequest {
        query: "completely unrelated query about databases".to_string(),
        path: None,
        project: None,
        limit: 10,
        min_score: 0.9, // Very high threshold
        hybrid: true,
    };

    let result = client.query_codebase(query_req).await;
    assert!(result.is_ok());
    // Adaptive threshold may or may not lower depending on similarity
}

#[tokio::test]
async fn test_query_codebase_validation_failure() {
    let (client, _temp_dir) = create_test_client().await;

    let request = QueryRequest {
        query: "   ".to_string(), // Empty query
        path: None,
        project: None,
        limit: 10,
        min_score: 0.7,
        hybrid: true,
    };

    let result = client.query_codebase(request).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("cannot be empty"));
}

// ===== search_with_filters Tests =====

#[tokio::test]
async fn test_search_with_filters_empty_index() {
    let (client, _temp_dir) = create_test_client().await;

    let request = AdvancedSearchRequest {
        query: "test".to_string(),
        path: None,
        project: None,
        limit: 10,
        min_score: 0.7,
        file_extensions: vec!["rs".to_string()],
        languages: vec!["Rust".to_string()],
        path_patterns: vec!["src/**".to_string()],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(response.results.len(), 0);
}

#[tokio::test]
async fn test_search_with_filters_validation_failure() {
    let (client, _temp_dir) = create_test_client().await;

    let request = AdvancedSearchRequest {
        query: "test".to_string(),
        path: None,
        project: None,
        limit: 10,
        min_score: 0.7,
        file_extensions: vec!["".to_string()], // Invalid
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("file extension cannot be empty")
    );
}

#[tokio::test]
async fn test_search_with_filters_with_data() {
    let (client, temp_dir) = create_test_client().await;

    // Create a directory structure for testing filters
    let data_dir = temp_dir.path().join("data");
    let src_dir = data_dir.join("src");
    std::fs::create_dir_all(&src_dir).unwrap();

    // Create Rust file
    std::fs::write(
        src_dir.join("auth.rs"),
        "fn authenticate_user(username: &str) -> bool { true }",
    )
    .unwrap();

    // Create Python file
    std::fs::write(
        src_dir.join("auth.py"),
        "def authenticate_user(username): return True",
    )
    .unwrap();

    // Index the data
    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("filter-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search with file extension filter for Rust only
    let request = AdvancedSearchRequest {
        query: "authenticate user".to_string(),
        path: None,
        project: Some("filter-test".to_string()),
        limit: 10,
        min_score: 0.3,
        file_extensions: vec!["rs".to_string()],
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // Should find results and all should be .rs files
    for result in &response.results {
        assert!(
            result.file_path.ends_with(".rs"),
            "Expected .rs file, got: {}",
            result.file_path
        );
    }
}

#[tokio::test]
async fn test_search_with_filters_adaptive_threshold_lowering() {
    let (client, temp_dir) = create_test_client().await;

    // Index some data
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(
        data_dir.join("code.rs"),
        "fn process_data() { /* some logic here */ }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("adaptive-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search with high threshold - should trigger adaptive lowering
    let request = AdvancedSearchRequest {
        query: "process data function".to_string(),
        path: None,
        project: Some("adaptive-test".to_string()),
        limit: 10,
        min_score: 0.9, // Very high threshold that will likely not match
        file_extensions: vec![],
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // If results were found, threshold should have been lowered
    if !response.results.is_empty() {
        assert!(
            response.threshold_lowered,
            "Expected threshold_lowered to be true when results found with high initial threshold"
        );
        assert!(
            response.threshold_used < 0.9,
            "Expected threshold_used ({}) to be lower than initial 0.9",
            response.threshold_used
        );
    }
}

#[tokio::test]
async fn test_search_with_filters_no_adaptive_when_results_found() {
    let (client, temp_dir) = create_test_client().await;

    // Index data with highly relevant content
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(
        data_dir.join("auth.rs"),
        "fn authenticate_user_with_password(username: &str, password: &str) -> Result<User, AuthError> { authenticate(username, password) }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("no-adaptive-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search with low threshold - should find results without lowering
    let request = AdvancedSearchRequest {
        query: "authenticate user password".to_string(),
        path: None,
        project: Some("no-adaptive-test".to_string()),
        limit: 10,
        min_score: 0.3, // Low threshold
        file_extensions: vec![],
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    if !response.results.is_empty() {
        // Threshold should NOT have been lowered since 0.3 is already low
        assert!(
            !response.threshold_lowered,
            "Expected threshold_lowered to be false when initial threshold is low"
        );
        assert_eq!(
            response.threshold_used, 0.3,
            "Expected threshold_used to remain at 0.3"
        );
    }
}

#[tokio::test]
async fn test_search_with_filters_language_filter() {
    let (client, temp_dir) = create_test_client().await;

    // Create files in different languages
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(
        data_dir.join("main.rs"),
        "fn main() { println!(\"Hello\"); }",
    )
    .unwrap();
    std::fs::write(data_dir.join("main.py"), "def main(): print('Hello')").unwrap();
    std::fs::write(
        data_dir.join("main.js"),
        "function main() { console.log('Hello'); }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("lang-filter-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search filtering by Rust language only
    let request = AdvancedSearchRequest {
        query: "main function".to_string(),
        path: None,
        project: Some("lang-filter-test".to_string()),
        limit: 10,
        min_score: 0.3,
        file_extensions: vec![],
        languages: vec!["Rust".to_string()],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // All results should be Rust
    for result in &response.results {
        assert_eq!(
            result.language, "Rust",
            "Expected Rust language, got: {}",
            result.language
        );
    }
}

#[tokio::test]
async fn test_search_with_filters_path_pattern() {
    let (client, temp_dir) = create_test_client().await;

    // Create nested directory structure
    let data_dir = temp_dir.path().join("data");
    let src_dir = data_dir.join("src");
    let tests_dir = data_dir.join("tests");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(&tests_dir).unwrap();

    std::fs::write(
        src_dir.join("lib.rs"),
        "pub fn add(a: i32, b: i32) -> i32 { a + b }",
    )
    .unwrap();
    std::fs::write(
        tests_dir.join("test_lib.rs"),
        "fn test_add() { assert_eq!(add(1, 2), 3); }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("path-pattern-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search with path pattern for src only
    let request = AdvancedSearchRequest {
        query: "add function".to_string(),
        path: None,
        project: Some("path-pattern-test".to_string()),
        limit: 10,
        min_score: 0.3,
        file_extensions: vec![],
        languages: vec![],
        path_patterns: vec!["**/src/**".to_string()],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // All results should be from src directory
    for result in &response.results {
        assert!(
            result.file_path.contains("src/") || result.file_path.starts_with("src/"),
            "Expected path to contain src/, got: {}",
            result.file_path
        );
    }
}

#[tokio::test]
async fn test_search_with_filters_combined_filters() {
    let (client, temp_dir) = create_test_client().await;

    // Create a complex directory structure
    let data_dir = temp_dir.path().join("data");
    let src_dir = data_dir.join("src");
    let lib_dir = data_dir.join("lib");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::create_dir_all(&lib_dir).unwrap();

    // Rust files in src
    std::fs::write(
        src_dir.join("handler.rs"),
        "pub fn handle_request() -> Response { Response::ok() }",
    )
    .unwrap();

    // Python files in src
    std::fs::write(
        src_dir.join("handler.py"),
        "def handle_request(): return Response.ok()",
    )
    .unwrap();

    // Rust files in lib
    std::fs::write(
        lib_dir.join("utils.rs"),
        "pub fn handle_utils() -> String { String::new() }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("combined-filter-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search with combined filters: Rust files in src directory only
    let request = AdvancedSearchRequest {
        query: "handle request".to_string(),
        path: None,
        project: Some("combined-filter-test".to_string()),
        limit: 10,
        min_score: 0.3,
        file_extensions: vec!["rs".to_string()],
        languages: vec!["Rust".to_string()],
        path_patterns: vec!["**/src/**".to_string()],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // All results should be Rust files in src directory
    for result in &response.results {
        assert!(
            result.file_path.ends_with(".rs"),
            "Expected .rs file, got: {}",
            result.file_path
        );
        assert!(
            result.file_path.contains("src/") || result.file_path.starts_with("src/"),
            "Expected path to contain src/, got: {}",
            result.file_path
        );
        assert_eq!(
            result.language, "Rust",
            "Expected Rust language, got: {}",
            result.language
        );
    }
}

#[tokio::test]
async fn test_search_with_filters_empty_query_validation() {
    let (client, _temp_dir) = create_test_client().await;

    let request = AdvancedSearchRequest {
        query: "   ".to_string(), // Empty/whitespace query
        path: None,
        project: None,
        limit: 10,
        min_score: 0.7,
        file_extensions: vec![],
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("cannot be empty"));
}

#[tokio::test]
async fn test_search_with_filters_threshold_boundary_at_0_3() {
    let (client, temp_dir) = create_test_client().await;

    // Index some data
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn test_function() {}").unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("boundary-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search with threshold at 0.3 - should NOT trigger adaptive lowering
    let request = AdvancedSearchRequest {
        query: "completely unrelated xyz abc 123".to_string(),
        path: None,
        project: Some("boundary-test".to_string()),
        limit: 10,
        min_score: 0.3, // At the boundary, should not lower further
        file_extensions: vec![],
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // Threshold should not be lowered below 0.3
    assert!(
        !response.threshold_lowered,
        "Threshold should not be lowered when already at 0.3"
    );
    assert_eq!(response.threshold_used, 0.3);
}

#[tokio::test]
async fn test_search_with_filters_multiple_extensions() {
    let (client, temp_dir) = create_test_client().await;

    // Create files with different extensions
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("code.rs"), "fn rust_code() {}").unwrap();
    std::fs::write(data_dir.join("code.ts"), "function tsCode() {}").unwrap();
    std::fs::write(data_dir.join("code.py"), "def python_code(): pass").unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("multi-ext-test".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(index_req).await.unwrap();

    // Search filtering by multiple extensions
    let request = AdvancedSearchRequest {
        query: "code function".to_string(),
        path: None,
        project: Some("multi-ext-test".to_string()),
        limit: 10,
        min_score: 0.3,
        file_extensions: vec!["rs".to_string(), "ts".to_string()],
        languages: vec![],
        path_patterns: vec![],
    };

    let result = client.search_with_filters(request).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // All results should be .rs or .ts files (not .py)
    for result in &response.results {
        assert!(
            result.file_path.ends_with(".rs") || result.file_path.ends_with(".ts"),
            "Expected .rs or .ts file, got: {}",
            result.file_path
        );
    }
}

// ===== get_statistics Tests =====

#[tokio::test]
async fn test_get_statistics_empty() {
    let (client, _temp_dir) = create_test_client().await;

    let result = client.get_statistics().await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert_eq!(response.total_files, 0);
    assert_eq!(response.total_chunks, 0);
    assert_eq!(response.total_embeddings, 0);
}

#[tokio::test]
async fn test_get_statistics_with_data() {
    let (client, temp_dir) = create_test_client().await;

    // Index some data
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn main() {}").unwrap();

    let request = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: None,
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(request).await.unwrap();

    // Get statistics
    let result = client.get_statistics().await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert!(response.total_files > 0);
    assert!(response.total_chunks > 0);
    assert!(response.total_embeddings > 0);
}

// ===== clear_index Tests =====

#[tokio::test]
async fn test_clear_index_empty() {
    let (client, _temp_dir) = create_test_client().await;

    let result = client.clear_index().await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert!(response.success);
}

#[tokio::test]
async fn test_clear_index_with_data() {
    let (client, temp_dir) = create_test_client().await;

    // Index some data
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn main() {}").unwrap();

    let request = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: None,
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(request).await.unwrap();

    // Clear the index
    let result = client.clear_index().await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert!(response.success);
    assert!(response.message.contains("Successfully cleared"));

    // Verify it's empty
    let stats = client.get_statistics().await.unwrap();
    assert_eq!(stats.total_files, 0);
}

// ===== search_git_history Tests =====

#[tokio::test]
async fn test_search_git_history_validation_failure() {
    let (client, _temp_dir) = create_test_client().await;

    let request = SearchGitHistoryRequest {
        query: "  ".to_string(), // Empty query
        path: ".".to_string(),
        project: None,
        branch: None,
        max_commits: 10,
        limit: 10,
        min_score: 0.7,
        author: None,
        since: None,
        until: None,
        file_pattern: None,
    };

    let result = client.search_git_history(request).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("cannot be empty"));
}

#[tokio::test]
async fn test_search_git_history_nonexistent_path() {
    let (client, _temp_dir) = create_test_client().await;

    let request = SearchGitHistoryRequest {
        query: "test".to_string(),
        path: "/nonexistent/path".to_string(),
        project: None,
        branch: None,
        max_commits: 10,
        limit: 10,
        min_score: 0.7,
        author: None,
        since: None,
        until: None,
        file_pattern: None,
    };

    let result = client.search_git_history(request).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("does not exist"));
}

// ===== Integration Tests =====

#[tokio::test]
async fn test_full_workflow_index_query_clear() {
    let (client, temp_dir) = create_test_client().await;

    // Step 1: Index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(
        data_dir.join("math.rs"),
        "fn add(a: i32, b: i32) -> i32 { a + b }",
    )
    .unwrap();

    let index_req = IndexRequest {
        path: data_dir.to_string_lossy().to_string(),
        project: Some("math-lib".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    let index_resp = client.index_codebase(index_req).await.unwrap();
    assert_eq!(index_resp.files_indexed, 1);

    // Step 2: Query
    let query_req = QueryRequest {
        query: "addition function".to_string(),
        path: None,
        project: Some("math-lib".to_string()),
        limit: 5,
        min_score: 0.3,
        hybrid: true,
    };
    let query_resp = client.query_codebase(query_req).await.unwrap();
    assert!(query_resp.results.len() > 0);

    // Step 3: Statistics
    let stats = client.get_statistics().await.unwrap();
    assert!(stats.total_files > 0);

    // Step 4: Clear
    let clear_resp = client.clear_index().await.unwrap();
    assert!(clear_resp.success);

    // Step 5: Verify empty
    let stats_after = client.get_statistics().await.unwrap();
    assert_eq!(stats_after.total_files, 0);
}

#[tokio::test]
async fn test_project_isolation() {
    let (client, temp_dir) = create_test_client().await;

    // Index for project A
    let data_dir_a = temp_dir.path().join("project_a");
    std::fs::create_dir(&data_dir_a).unwrap();
    std::fs::write(data_dir_a.join("a.rs"), "fn project_a() {}").unwrap();

    let req_a = IndexRequest {
        path: data_dir_a.to_string_lossy().to_string(),
        project: Some("project-a".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(req_a).await.unwrap();

    // Index for project B
    let data_dir_b = temp_dir.path().join("project_b");
    std::fs::create_dir(&data_dir_b).unwrap();
    std::fs::write(data_dir_b.join("b.rs"), "fn project_b() {}").unwrap();

    let req_b = IndexRequest {
        path: data_dir_b.to_string_lossy().to_string(),
        project: Some("project-b".to_string()),
        include_patterns: vec![],
        exclude_patterns: vec![],
        max_file_size: 1024 * 1024,
    };
    client.index_codebase(req_b).await.unwrap();

    // Query only project A
    let query_a = QueryRequest {
        query: "project".to_string(),
        path: None,
        project: Some("project-a".to_string()),
        limit: 10,
        min_score: 0.3,
        hybrid: true,
    };
    let results_a = client.query_codebase(query_a).await.unwrap();

    // Results should only be from project A
    for result in results_a.results {
        assert_eq!(result.project, Some("project-a".to_string()));
    }
}

// ===== Concurrent Indexing Lock Tests =====

#[tokio::test]
async fn test_index_lock_prevents_duplicate_indexing() {
    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(
        data_dir.join("test.rs"),
        "fn main() { println!(\"test\"); }",
    )
    .unwrap();

    let path = data_dir.to_string_lossy().to_string();

    // Start first indexing
    let lock_result1 = client.try_acquire_index_lock(&path).await.unwrap();
    assert!(
        matches!(lock_result1, IndexLockResult::Acquired(_)),
        "First call should acquire the lock"
    );

    // Try to acquire lock again while first is still held
    let lock_result2 = client.try_acquire_index_lock(&path).await.unwrap();
    // With cross-process locking, this could be WaitForResult (same process, in-memory)
    // or WaitForFilesystemLock (different process holding filesystem lock)
    assert!(
        matches!(
            lock_result2,
            IndexLockResult::WaitForResult(_) | IndexLockResult::WaitForFilesystemLock(_)
        ),
        "Second call should wait for the first operation (got: {:?})",
        match &lock_result2 {
            IndexLockResult::Acquired(_) => "Acquired",
            IndexLockResult::WaitForResult(_) => "WaitForResult",
            IndexLockResult::WaitForFilesystemLock(_) => "WaitForFilesystemLock",
        }
    );

    // Release the first lock by dropping it (simulate completion)
    if let IndexLockResult::Acquired(guard) = lock_result1 {
        // Broadcast a result before releasing
        let result = IndexResponse {
            mode: crate::rag::types::IndexingMode::Full,
            files_indexed: 1,
            chunks_created: 1,
            embeddings_generated: 1,
            duration_ms: 100,
            errors: vec![],
            files_updated: 0,
            files_removed: 0,
        };
        guard.broadcast_result(&result);
        guard.release().await;
    }
}

#[tokio::test]
async fn test_index_lock_waiters_receive_result() {
    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn test() {}").unwrap();

    let path = data_dir.to_string_lossy().to_string();

    // Acquire the lock first
    let lock_result = client.try_acquire_index_lock(&path).await.unwrap();
    let guard = match lock_result {
        IndexLockResult::Acquired(g) => g,
        _ => panic!("Expected to acquire lock"),
    };

    // Try to get a waiter - with filesystem locking, this returns WaitForFilesystemLock
    // since the filesystem lock is held by the first guard
    let lock_result2 = client.try_acquire_index_lock(&path).await.unwrap();

    match lock_result2 {
        IndexLockResult::WaitForFilesystemLock(_) => {
            // Expected behavior with cross-process filesystem locking
            // Release the first lock
            guard.broadcast_result(&IndexResponse {
                mode: crate::rag::types::IndexingMode::Full,
                files_indexed: 42,
                chunks_created: 100,
                embeddings_generated: 100,
                duration_ms: 500,
                errors: vec![],
                files_updated: 0,
                files_removed: 0,
            });
            guard.release().await;

            // Verify lock can now be acquired
            let lock_result3 = client.try_acquire_index_lock(&path).await.unwrap();
            assert!(
                matches!(lock_result3, IndexLockResult::Acquired(_)),
                "Should acquire lock after first is released"
            );
        }
        IndexLockResult::WaitForResult(mut receiver) => {
            // In-process waiting (would only happen if same process, same in-memory state)
            let expected_response = IndexResponse {
                mode: crate::rag::types::IndexingMode::Full,
                files_indexed: 42,
                chunks_created: 100,
                embeddings_generated: 100,
                duration_ms: 500,
                errors: vec![],
                files_updated: 0,
                files_removed: 0,
            };
            guard.broadcast_result(&expected_response);
            guard.release().await;

            let received = receiver.recv().await.unwrap();
            assert_eq!(received.files_indexed, 42);
            assert_eq!(received.chunks_created, 100);
            assert_eq!(received.embeddings_generated, 100);
        }
        IndexLockResult::Acquired(_) => {
            panic!("Second call should NOT acquire lock while first is held");
        }
    }
}

#[tokio::test]
async fn test_index_lock_path_normalization() {
    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn test() {}").unwrap();

    // Get different path representations
    let path1 = data_dir.to_string_lossy().to_string();
    let path2 = format!("{}/../data", data_dir.to_string_lossy()); // With ..

    // Acquire lock with first path
    let lock_result1 = client.try_acquire_index_lock(&path1).await.unwrap();
    assert!(matches!(lock_result1, IndexLockResult::Acquired(_)));

    // Try to acquire with different but equivalent path
    // With filesystem locking, this returns WaitForFilesystemLock (cross-process)
    // Both WaitForResult and WaitForFilesystemLock indicate the lock is shared
    let lock_result2 = client.try_acquire_index_lock(&path2).await.unwrap();
    assert!(
        matches!(
            lock_result2,
            IndexLockResult::WaitForResult(_) | IndexLockResult::WaitForFilesystemLock(_)
        ),
        "Equivalent paths should share the same lock"
    );

    // Release the first lock
    if let IndexLockResult::Acquired(guard) = lock_result1 {
        let result = IndexResponse {
            mode: crate::rag::types::IndexingMode::Full,
            files_indexed: 1,
            chunks_created: 1,
            embeddings_generated: 1,
            duration_ms: 100,
            errors: vec![],
            files_updated: 0,
            files_removed: 0,
        };
        guard.broadcast_result(&result);
        guard.release().await;
    }
}

#[tokio::test]
async fn test_index_lock_released_after_completion() {
    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn test() {}").unwrap();

    let path = data_dir.to_string_lossy().to_string();

    // First: acquire, broadcast, release
    {
        let lock_result = client.try_acquire_index_lock(&path).await.unwrap();
        let guard = match lock_result {
            IndexLockResult::Acquired(g) => g,
            _ => panic!("Expected to acquire lock"),
        };

        let result = IndexResponse {
            mode: crate::rag::types::IndexingMode::Full,
            files_indexed: 1,
            chunks_created: 1,
            embeddings_generated: 1,
            duration_ms: 100,
            errors: vec![],
            files_updated: 0,
            files_removed: 0,
        };
        guard.broadcast_result(&result);
        guard.release().await;
    }

    // Second: should be able to acquire lock again
    let lock_result2 = client.try_acquire_index_lock(&path).await.unwrap();
    assert!(
        matches!(lock_result2, IndexLockResult::Acquired(_)),
        "Should be able to acquire lock after previous operation completed"
    );

    // Clean up
    if let IndexLockResult::Acquired(guard) = lock_result2 {
        let result = IndexResponse {
            mode: crate::rag::types::IndexingMode::Incremental,
            files_indexed: 0,
            chunks_created: 0,
            embeddings_generated: 0,
            duration_ms: 50,
            errors: vec![],
            files_updated: 0,
            files_removed: 0,
        };
        guard.broadcast_result(&result);
        guard.release().await;
    }
}

#[tokio::test]
async fn test_concurrent_index_calls_share_result() {
    use std::sync::Arc;
    use tokio::sync::Barrier;

    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn main() {}").unwrap();

    let path = data_dir.to_string_lossy().to_string();
    let client = Arc::new(client);

    // Use a barrier to synchronize the start of both tasks
    let barrier = Arc::new(Barrier::new(2));

    let client1 = client.clone();
    let path1 = path.clone();
    let barrier1 = barrier.clone();

    let client2 = client.clone();
    let path2 = path.clone();
    let barrier2 = barrier.clone();

    // Spawn two concurrent indexing tasks
    let task1 = tokio::spawn(async move {
        barrier1.wait().await;
        let request = IndexRequest {
            path: path1,
            project: None,
            include_patterns: vec![],
            exclude_patterns: vec![],
            max_file_size: 1024 * 1024,
        };
        client1.index_codebase(request).await
    });

    let task2 = tokio::spawn(async move {
        barrier2.wait().await;
        let request = IndexRequest {
            path: path2,
            project: None,
            include_patterns: vec![],
            exclude_patterns: vec![],
            max_file_size: 1024 * 1024,
        };
        client2.index_codebase(request).await
    });

    // Wait for both to complete
    let (result1, result2) = tokio::join!(task1, task2);

    // Both should succeed (no errors)
    let resp1 = result1.unwrap().unwrap();
    let resp2 = result2.unwrap().unwrap();

    // With filesystem locking, the behaviors are:
    // - One task does full indexing (files_indexed > 0)
    // - Other task either receives broadcast (same result) OR
    //   waits for filesystem lock then returns immediately (files_indexed = 0)
    //
    // The important thing is both succeed without errors
    assert!(
        resp1.errors.is_empty(),
        "Task 1 should succeed without errors"
    );
    assert!(
        resp2.errors.is_empty(),
        "Task 2 should succeed without errors"
    );

    // At least one should have done the actual indexing
    let total_indexed = resp1.files_indexed + resp2.files_indexed;
    assert!(
        total_indexed >= 1,
        "At least one task should have indexed files"
    );
}

#[tokio::test]
async fn test_index_lock_drop_without_release_broadcasts_error() {
    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn test() {}").unwrap();

    let path = data_dir.to_string_lossy().to_string();

    // Acquire the lock
    let lock_result = client.try_acquire_index_lock(&path).await.unwrap();
    let guard = match lock_result {
        IndexLockResult::Acquired(g) => g,
        _ => panic!("Expected to acquire lock"),
    };

    // Get a waiter - with filesystem locking, we get WaitForFilesystemLock
    let lock_result2 = client.try_acquire_index_lock(&path).await.unwrap();
    match lock_result2 {
        IndexLockResult::WaitForFilesystemLock(_) => {
            // With filesystem locking, the second call gets blocked on the filesystem lock
            // Drop the guard - this releases the filesystem lock
            drop(guard);

            // Give cleanup time to run
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

            // Now we should be able to acquire the lock
            let lock_result3 = client.try_acquire_index_lock(&path).await.unwrap();
            assert!(
                matches!(lock_result3, IndexLockResult::Acquired(_)),
                "Should acquire after first is dropped"
            );
        }
        IndexLockResult::WaitForResult(mut receiver) => {
            // In-process waiting path (legacy behavior)
            // Drop the guard WITHOUT calling broadcast_result or release
            drop(guard);

            // Give the async cleanup task time to run
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

            // Waiter should receive an error response (not hang forever)
            let received = receiver.recv().await.unwrap();
            assert_eq!(received.files_indexed, 0);
            assert!(!received.errors.is_empty());
            assert!(received.errors[0].contains("interrupted"));
        }
        IndexLockResult::Acquired(_) => {
            panic!("Second call should NOT acquire lock while first is held");
        }
    }
}

#[tokio::test]
async fn test_index_lock_can_reacquire_after_drop_without_release() {
    let (client, temp_dir) = create_test_client().await;

    // Create data to index
    let data_dir = temp_dir.path().join("data");
    std::fs::create_dir(&data_dir).unwrap();
    std::fs::write(data_dir.join("test.rs"), "fn test() {}").unwrap();

    let path = data_dir.to_string_lossy().to_string();

    // Acquire and immediately drop (simulating panic)
    {
        let lock_result = client.try_acquire_index_lock(&path).await.unwrap();
        match lock_result {
            IndexLockResult::Acquired(_guard) => {
                // Drop without release
            }
            _ => panic!("Expected to acquire lock"),
        }
    }

    // Give the async cleanup task time to run
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    // Should be able to acquire lock again
    let lock_result2 = client.try_acquire_index_lock(&path).await.unwrap();
    assert!(
        matches!(lock_result2, IndexLockResult::Acquired(_)),
        "Should be able to acquire lock after previous guard was dropped"
    );

    // Clean up properly this time
    if let IndexLockResult::Acquired(guard) = lock_result2 {
        let result = IndexResponse {
            mode: crate::rag::types::IndexingMode::Full,
            files_indexed: 1,
            chunks_created: 1,
            embeddings_generated: 1,
            duration_ms: 100,
            errors: vec![],
            files_updated: 0,
            files_removed: 0,
        };
        guard.broadcast_result(&result);
        guard.release().await;
    }
}