claudix 0.1.2

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

use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use serde::Serialize;
use tokio::fs;
use tokio::sync::mpsc;

use crate::config::{self, validate_project_relative_path};
use crate::enumeration::WatchFilter;
use crate::error::{ClaudixError, RecoveryHint, Result};
use crate::hooks::HookEvent;
use crate::search::SearchQuery;
use crate::store::{IndexLockGuard, Store};
use crate::types::{Language, RelativePath};
use crate::{Claudix, IndexFileStatus, IndexProgress};

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SearchHit {
    pub file_path: String,
    pub language: String,
    pub kind: String,
    pub name: Option<String>,
    pub line_start: u32,
    pub line_end: u32,
    pub score: f32,
    pub stale: bool,
    pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SearchOutput {
    pub hits: Vec<SearchHit>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IndexOutput {
    pub file_count: usize,
    pub chunk_count: usize,
}

pub struct StderrIndexProgress;

impl IndexProgress for StderrIndexProgress {
    fn file(&mut self, path: &RelativePath, status: IndexFileStatus) -> Result<()> {
        let mut stderr = io::stderr().lock();
        match status {
            IndexFileStatus::Indexed => writeln!(stderr, "indexed {}", path.as_str())?,
            IndexFileStatus::Verified => writeln!(stderr, "verified {}", path.as_str())?,
            IndexFileStatus::Skipped(reason) => {
                writeln!(stderr, "skipped {}: {reason}", path.as_str())?
            }
        }
        stderr.flush()?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ClearOutput {
    pub cleared: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StatusOutput {
    pub chunk_count: usize,
    pub file_count: usize,
    pub model: Option<String>,
    pub dimensions: Option<u16>,
    pub last_full_index_at: Option<String>,
    pub last_incremental_at: Option<String>,
    /// True when the index is missing or older than `reindex_after_hours`.
    pub stale: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoctorOutput {
    pub project_root: String,
    pub index_present: bool,
    pub chunk_count: usize,
    pub file_count: usize,
    pub model: Option<String>,
    pub dimensions: Option<u16>,
    pub embedding_provider: String,
    pub embedding_healthy: bool,
    /// True when the stored index model differs from the active config model.
    /// Distinct from `embedding_healthy = false` caused by the server being unreachable.
    pub embedding_model_mismatch: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstallOutput {
    pub plugin_root: String,
    pub binary_path: String,
    pub config_path: String,
    pub wrote_config: bool,
    pub embedding_healthy: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SetupState {
    Ready,
    Missing(Vec<&'static str>),
}

pub async fn run_search(
    project_root: impl AsRef<Path>,
    query: String,
    top_k: Option<usize>,
    language_filter: Option<Vec<String>>,
    path_prefix: Option<String>,
) -> Result<SearchOutput> {
    validate_search_query(&query)?;
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let top_k = top_k.unwrap_or(config.search.top_k);
    validate_search_top_k(top_k)?;
    let claudix = Claudix::new(project_root, Arc::new(config)).await?;

    run_search_with_claudix(&claudix, query, top_k, language_filter, path_prefix).await
}

pub async fn run_index(project_root: impl AsRef<Path>) -> Result<IndexOutput> {
    let session = IndexSession::new(project_root).await?;
    let stats = session.claudix.index_full().await?;

    Ok(IndexOutput {
        file_count: stats.file_count,
        chunk_count: stats.chunk_count,
    })
}

pub async fn run_index_with_progress(project_root: impl AsRef<Path>) -> Result<IndexOutput> {
    let session = IndexSession::new(project_root).await?;
    let mut progress = StderrIndexProgress;
    let stats = session
        .claudix
        .index_full_with_progress(&mut progress)
        .await?;

    Ok(IndexOutput {
        file_count: stats.file_count,
        chunk_count: stats.chunk_count,
    })
}

struct IndexSession {
    claudix: Claudix,
    _lock: IndexLockGuard,
}

impl IndexSession {
    async fn new(project_root: impl AsRef<Path>) -> Result<Self> {
        let project_root = canonical_project_root(project_root.as_ref())?;
        require_git_repo(&project_root)?;
        let config = config::load(&project_root)?;
        let store = Store::new(&project_root, &config)?;
        let lock = store
            .acquire_index_lock()
            .ok_or_else(|| crate::error::ClaudixError::Store("index already running".to_owned()))?;
        let claudix = match Claudix::new(project_root.clone(), Arc::new(config.clone())).await {
            Ok(claudix) => claudix,
            Err(error) if requires_clean_reindex(&error) => {
                store.clear_chunks(&config).await?;
                Claudix::new(project_root, Arc::new(config)).await?
            }
            Err(error) => return Err(error),
        };

        Ok(Self {
            claudix,
            _lock: lock,
        })
    }
}

pub async fn run_status(project_root: impl AsRef<Path>) -> Result<StatusOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;
    status_from_store(&store, &config).await
}

const WATCH_MARKER_FILE_NAME: &str = "watch.pid";
const WATCH_HEARTBEAT_SECS: u64 = 30;

struct WatchMarkerGuard {
    path: PathBuf,
}

impl WatchMarkerGuard {
    /// Claim the watcher marker for this process.
    ///
    /// Coordinates with `spawn_background_watch`, which `create_new`s the marker
    /// and pre-writes the spawned child's PID — that hand-off case finds our own
    /// PID already stored and adopts the file. A stale marker (PID dead) is
    /// reclaimed; a live foreign PID returns an error so the duplicate watcher
    /// exits instead of clobbering the original.
    fn install(path: PathBuf) -> Result<Self> {
        use std::fs::OpenOptions;
        use std::io::Write;

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let my_pid = std::process::id();
        for _ in 0..2 {
            if let Ok(mut file) = OpenOptions::new().write(true).create_new(true).open(&path) {
                let _ = writeln!(file, "{my_pid}");
                return Ok(Self { path });
            }

            let existing = std::fs::read_to_string(&path)
                .ok()
                .and_then(|content| content.trim().parse::<u32>().ok());
            match existing {
                Some(pid) if pid == my_pid => {
                    let _ = std::fs::write(&path, format!("{my_pid}\n"));
                    return Ok(Self { path });
                }
                Some(pid) if !crate::store::process_running(pid) => {
                    let _ = std::fs::remove_file(&path);
                }
                Some(_) => {
                    return Err(ClaudixError::Store(
                        "another claudix watch process is already running".to_owned(),
                    ));
                }
                None => {
                    let _ = std::fs::remove_file(&path);
                }
            }
        }
        Err(ClaudixError::Store(
            "watcher marker claim failed".to_owned(),
        ))
    }

    fn heartbeat(&self) {
        let _ = std::fs::write(&self.path, std::process::id().to_string());
    }
}

impl Drop for WatchMarkerGuard {
    fn drop(&mut self) {
        // Only remove if we still hold the marker. Another process may have
        // reclaimed it after our heartbeat task stalled (e.g. SIGSTOP).
        let existing = std::fs::read_to_string(&self.path)
            .ok()
            .and_then(|content| content.trim().parse::<u32>().ok());
        if existing == Some(std::process::id()) {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

pub async fn run_watch(project_root: impl AsRef<Path>) -> Result<()> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    if !config.watch {
        return Ok(());
    }

    let store = Store::new(&project_root, &config)?;
    store.ensure_layout()?;
    let marker = Arc::new(WatchMarkerGuard::install(
        store.state_dir_path().join(WATCH_MARKER_FILE_NAME),
    )?);

    // Cold ONNX loads can exceed the marker stale window; refresh the marker
    // from a side task while the watcher itself is still booting so concurrent
    // SessionStarts do not misclassify us as dead and spawn a duplicate.
    let early_heartbeat = {
        let marker = Arc::clone(&marker);
        tokio::spawn(async move {
            let mut tick = tokio::time::interval(Duration::from_secs(WATCH_HEARTBEAT_SECS));
            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
            tick.tick().await; // consume the immediate first tick
            loop {
                tick.tick().await;
                marker.heartbeat();
            }
        })
    };

    let (event_tx, mut event_rx) = mpsc::unbounded_channel();
    let mut watcher = RecommendedWatcher::new(
        move |event| {
            let _ = event_tx.send(event);
        },
        notify::Config::default(),
    )
    .map_err(|error| ClaudixError::Store(format!("file watcher failed: {error}")))?;
    watcher
        .watch(&project_root, RecursiveMode::Recursive)
        .map_err(|error| ClaudixError::Store(format!("file watcher failed: {error}")))?;

    let filter = WatchFilter::load(&project_root)?;
    let claudix = Claudix::new(project_root.clone(), Arc::new(config)).await?;

    early_heartbeat.abort();
    let _ = early_heartbeat.await;

    let mut pending = VecDeque::new();
    let mut debounce_deadline: Option<tokio::time::Instant> = None;
    let mut heartbeat = tokio::time::interval(Duration::from_secs(WATCH_HEARTBEAT_SECS));
    heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    heartbeat.tick().await; // first tick fires immediately; consume it before the loop
    loop {
        tokio::select! {
            event = event_rx.recv() => {
                let Some(event) = event else {
                    return Ok(());
                };
                queue_reindex_paths(&project_root, &filter, event, &mut pending);
                // Anchor the debounce window when the first event lands; further
                // events do NOT extend it so a continuous file-event stream
                // still gets drained on schedule instead of starving.
                if debounce_deadline.is_none() && !pending.is_empty() {
                    debounce_deadline =
                        Some(tokio::time::Instant::now() + Duration::from_millis(250));
                }
            }
            _ = async {
                match debounce_deadline {
                    Some(deadline) => tokio::time::sleep_until(deadline).await,
                    None => std::future::pending::<()>().await,
                }
            } => {
                debounce_deadline = None;
                let paths = drain_unique_paths(&mut pending);
                for path in paths {
                    // Serialize against concurrent reindex-file CLI/MCP calls and
                    // any duplicate watcher that slipped through the marker claim.
                    let _reindex_lock = match store.acquire_reindex_lock() {
                        Ok(lock) => lock,
                        Err(error) => {
                            tracing::warn!(
                                "claudix watch skipped reindex of {}: {error}",
                                path.display()
                            );
                            continue;
                        }
                    };
                    if let Err(error) = claudix.reindex_file(&path).await {
                        tracing::warn!("claudix watch failed to reindex {}: {error}", path.display());
                    }
                }
            }
            _ = heartbeat.tick() => {
                marker.heartbeat();
            }
        }
    }
}

pub async fn run_reindex_file(
    project_root: impl AsRef<Path>,
    path: impl AsRef<Path>,
) -> Result<IndexOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;

    // Block on the shared chunk-writer lock instead of short-circuiting on a
    // running full index: bailing here loses the user's edit until they save
    // again, since the reindex-file child returns 0 with no retry path.
    let _reindex_lock = store.acquire_reindex_lock()?;
    let claudix = Claudix::new(project_root, Arc::new(config)).await?;
    let stats = claudix.reindex_file(path.as_ref()).await?;

    Ok(IndexOutput {
        file_count: stats.file_count,
        chunk_count: stats.chunk_count,
    })
}

pub async fn run_doctor(project_root: impl AsRef<Path>) -> Result<DoctorOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;
    let status = status_from_store(&store, &config).await?;

    let claudix = Claudix::new(project_root.clone(), Arc::new(config.clone())).await;
    let (embedding_healthy, embedding_model_mismatch) = match claudix {
        Ok(claudix) => (claudix.embedder_health_check().await.is_ok(), false),
        Err(ClaudixError::EmbeddingModelMismatch { .. }) => (false, true),
        Err(_) => (false, false),
    };

    Ok(DoctorOutput {
        project_root: project_root.display().to_string(),
        index_present: status.chunk_count > 0 || status.model.is_some(),
        chunk_count: status.chunk_count,
        file_count: status.file_count,
        model: status.model,
        dimensions: status.dimensions,
        embedding_provider: match config.embedding.provider {
            config::EmbeddingProvider::Bundled => "bundled".to_owned(),
            config::EmbeddingProvider::Http => "http".to_owned(),
        },
        embedding_healthy,
        embedding_model_mismatch,
    })
}

pub async fn run_clear_index(project_root: impl AsRef<Path>) -> Result<ClearOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;
    store.clear_chunks(&config).await?;

    Ok(ClearOutput { cleared: true })
}

fn requires_clean_reindex(error: &ClaudixError) -> bool {
    matches!(
        error,
        ClaudixError::SchemaMismatch { .. }
            | ClaudixError::EmbeddingModelMismatch { .. }
            | ClaudixError::DimensionMismatch { .. }
    )
}

fn queue_reindex_paths(
    project_root: &Path,
    filter: &WatchFilter,
    event: notify::Result<notify::Event>,
    pending: &mut VecDeque<PathBuf>,
) {
    let Ok(event) = event else {
        return;
    };
    if !is_reindex_event(&event.kind) {
        return;
    }

    pending.extend(event.paths.into_iter().filter_map(|path| {
        let relative = path.strip_prefix(project_root).ok()?;
        relative.components().next()?;
        if !filter.is_watchable(relative) {
            return None;
        }
        Some(relative.to_path_buf())
    }));
}

fn is_reindex_event(kind: &EventKind) -> bool {
    matches!(
        kind,
        EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
    )
}

fn drain_unique_paths(pending: &mut VecDeque<PathBuf>) -> Vec<PathBuf> {
    let mut seen = HashSet::new();
    let mut paths = Vec::new();
    while let Some(path) = pending.pop_front() {
        if seen.insert(path.clone()) {
            paths.push(path);
        }
    }
    paths
}

pub async fn run_install(project_root: impl AsRef<Path>) -> Result<InstallOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let source_root = install_source_root(&project_root)?;
    let plugin_root = plugin_root_from_env(&project_root, std::env::var_os("CLAUDE_PLUGIN_ROOT"))?;
    let binary_path = plugin_root.join("bin").join("claudix");
    let config_path = global_config_path()?;

    install_plugin_assets(&source_root, &plugin_root).await?;

    let wrote_config = ensure_global_config(&config_path).await?;
    let config = config::load(&project_root)?;
    let claudix = Claudix::new(project_root, Arc::new(config)).await?;
    let embedding_healthy = claudix.embedder_health_check().await.is_ok();

    Ok(InstallOutput {
        plugin_root: plugin_root.display().to_string(),
        binary_path: binary_path.display().to_string(),
        config_path: config_path.display().to_string(),
        wrote_config,
        embedding_healthy,
    })
}

pub async fn setup_state(project_root: impl AsRef<Path>) -> SetupState {
    let project_root = project_root.as_ref();
    let mut missing = Vec::new();

    if plugin_root_from_env(project_root, std::env::var_os("CLAUDE_PLUGIN_ROOT")).is_err() {
        missing.push("plugin files");
    }
    match global_config_path() {
        Ok(config_path) if config_path.try_exists().unwrap_or(false) => {}
        _ => missing.push("global config"),
    }
    if config::load(project_root).is_err() {
        missing.push("valid config");
    }

    if missing.is_empty() {
        SetupState::Ready
    } else {
        SetupState::Missing(missing)
    }
}

pub fn parse_hook_event(value: &str) -> Result<HookEvent> {
    match value {
        "SessionStart" => Ok(HookEvent::SessionStart),
        "PostToolUse" => Ok(HookEvent::PostToolUse),
        "PreToolUse" => Ok(HookEvent::PreToolUse),
        "UserPromptSubmit" => Ok(HookEvent::UserPromptSubmit),
        _ => Err(ClaudixError::ConfigInvalid {
            message: format!("unknown hook event: {value}"),
            recovery: RecoveryHint(
                "Use one of: SessionStart, PostToolUse, PreToolUse, UserPromptSubmit",
            ),
        }),
    }
}

async fn run_search_with_claudix(
    claudix: &Claudix,
    query: String,
    top_k: usize,
    language_filter: Option<Vec<String>>,
    path_prefix: Option<String>,
) -> Result<SearchOutput> {
    validate_search_top_k(top_k)?;
    let query = SearchQuery {
        query,
        top_k,
        language_filter: parse_language_filter(language_filter)?,
        path_prefix: parse_path_prefix(path_prefix)?,
    };
    let results = claudix.search(query).await?;

    Ok(SearchOutput {
        hits: results
            .into_iter()
            .map(|result| SearchHit {
                file_path: result.chunk.file_path.to_string(),
                language: result.chunk.language.to_string(),
                kind: result.chunk.kind.to_string(),
                name: result.chunk.name,
                line_start: result.chunk.line_range.start,
                line_end: result.chunk.line_range.end,
                score: result.score,
                stale: result.stale,
                snippet: result.chunk.content,
            })
            .collect(),
    })
}

async fn status_from_store(store: &Store, config: &crate::config::Config) -> Result<StatusOutput> {
    let manifest = store.read_manifest()?;
    let chunk_count = manifest
        .as_ref()
        .map(|m| m.chunk_count as usize)
        .unwrap_or(0);
    let file_count = manifest
        .as_ref()
        .map(|m| m.file_count as usize)
        .unwrap_or(0);

    let stale = manifest
        .as_ref()
        .map(|m| crate::hooks::index_is_stale(m, config))
        .unwrap_or(true);

    Ok(StatusOutput {
        chunk_count,
        file_count,
        model: manifest
            .as_ref()
            .map(|manifest| manifest.embedding_model.clone()),
        dimensions: manifest.as_ref().map(|manifest| manifest.dimensions),
        last_full_index_at: manifest
            .as_ref()
            .and_then(|manifest| manifest.last_full_index_at.clone()),
        last_incremental_at: manifest
            .as_ref()
            .and_then(|manifest| manifest.last_incremental_at.clone()),
        stale,
    })
}

async fn install_plugin_assets(project_root: &Path, plugin_root: &Path) -> Result<bool> {
    let mut changed = false;
    changed |= copy_plugin_asset(
        project_root,
        ".claude-plugin/plugin.json",
        plugin_root.join(".claude-plugin").join("plugin.json"),
    )
    .await?;
    changed |= copy_plugin_asset(
        project_root,
        "hooks/hooks.json",
        plugin_root.join("hooks").join("hooks.json"),
    )
    .await?;
    changed |= copy_plugin_asset(
        project_root,
        "bin/claudix",
        plugin_root.join("bin").join("claudix"),
    )
    .await?;
    make_executable(&plugin_root.join("bin").join("claudix")).await?;
    changed |=
        copy_plugin_directory(project_root, "commands", plugin_root.join("commands")).await?;
    changed |= copy_plugin_directory(project_root, "scripts", plugin_root.join("scripts")).await?;
    Ok(changed)
}

async fn copy_plugin_asset(
    project_root: &Path,
    source_relative: &str,
    destination: PathBuf,
) -> Result<bool> {
    let source = required_plugin_asset(project_root, source_relative).await?;

    if source == destination || files_match(&source, &destination).await? {
        return Ok(false);
    }

    if let Some(parent) = destination.parent() {
        fs::create_dir_all(parent).await?;
    }
    fs::copy(source, &destination).await?;
    Ok(true)
}

async fn copy_plugin_directory(
    project_root: &Path,
    source_relative: &str,
    destination: PathBuf,
) -> Result<bool> {
    let source = required_plugin_asset(project_root, source_relative).await?;
    if source == destination || directories_match(&source, &destination).await? {
        return Ok(false);
    }

    if fs::try_exists(&destination).await? {
        fs::remove_dir_all(&destination).await?;
    }
    fs::create_dir_all(&destination).await?;

    let mut entries = fs::read_dir(source).await?;
    while let Some(entry) = entries.next_entry().await? {
        let file_type = entry.file_type().await?;
        if file_type.is_file() {
            let destination_file = destination.join(entry.file_name());
            fs::copy(entry.path(), &destination_file).await?;
            if destination_file
                .extension()
                .is_some_and(|extension| extension == "sh")
            {
                make_executable(&destination_file).await?;
            }
        }
    }

    Ok(true)
}

async fn files_match(left: &Path, right: &Path) -> Result<bool> {
    if !fs::try_exists(right).await? {
        return Ok(false);
    }

    let left_metadata = fs::metadata(left).await?;
    let right_metadata = fs::metadata(right).await?;
    if left_metadata.len() != right_metadata.len() {
        return Ok(false);
    }

    Ok(fs::read(left).await? == fs::read(right).await?)
}

async fn directories_match(left: &Path, right: &Path) -> Result<bool> {
    if !fs::try_exists(right).await? {
        return Ok(false);
    }

    let mut left_entries = directory_file_names(left).await?;
    let mut right_entries = directory_file_names(right).await?;
    left_entries.sort();
    right_entries.sort();
    if left_entries != right_entries {
        return Ok(false);
    }

    for entry in left_entries {
        if !files_match(&left.join(&entry), &right.join(&entry)).await? {
            return Ok(false);
        }
    }

    Ok(true)
}

async fn directory_file_names(path: &Path) -> Result<Vec<std::ffi::OsString>> {
    let mut file_names = Vec::new();
    let mut entries = fs::read_dir(path).await?;
    while let Some(entry) = entries.next_entry().await? {
        if entry.file_type().await?.is_file() {
            file_names.push(entry.file_name());
        }
    }
    Ok(file_names)
}

async fn required_plugin_asset(project_root: &Path, source_relative: &str) -> Result<PathBuf> {
    let source = project_root.join(source_relative);
    if fs::try_exists(&source).await? {
        return Ok(source);
    }

    Err(ClaudixError::ConfigInvalid {
        message: format!("required plugin asset missing: {}", source.display()),
        recovery: RecoveryHint("Restore the plugin metadata files before running claudix install"),
    })
}

fn local_plugin_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join("claudix-plugin")
}

async fn make_executable(path: &Path) -> Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        let mut permissions = fs::metadata(path).await?.permissions();
        permissions.set_mode(0o755);
        fs::set_permissions(path, permissions).await?;
    }

    Ok(())
}

async fn ensure_global_config(config_path: &Path) -> Result<bool> {
    if fs::try_exists(config_path).await? {
        return Ok(false);
    }

    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent).await?;
    }

    fs::write(config_path, default_global_config()).await?;
    Ok(true)
}

fn default_global_config() -> &'static str {
    "\
# Global claudix configuration — uncomment and edit as needed.
# Project-level overrides go in .claude/claudix.toml (project wins).
# watch = false                  # opt-in file watcher for saved files

[embedding]
# provider = \"bundled\"           # bundled | http
# model = \"bge-small-en-v1.5\"    # only used by bundled provider
# dimensions = 384               # must match the model
# endpoint = \"http://localhost:11434\"  # for http provider (LM Studio / Ollama)

[indexing]
# reindex_after_hours = 24       # auto-reindex threshold on session start

[hooks]
# auto_index_on_session_start = true  # trigger background reindex when stale
# intercept_grep = true               # redirect conceptual Grep/rg to search_code
# auto_reembed_on_edit = true         # re-embed edited files in background

[search]
# top_k = 10                     # default result count for search_code
"
}

fn install_source_root(project_root: &Path) -> Result<PathBuf> {
    if is_claudix_plugin_root(project_root) {
        return Ok(project_root.to_path_buf());
    }

    match std::env::var_os("CLAUDE_PLUGIN_ROOT") {
        Some(path) => Ok(PathBuf::from(path)),
        None => Ok(PathBuf::from(env!("CARGO_MANIFEST_DIR"))),
    }
}

fn plugin_root_from_env(
    project_root: &Path,
    plugin_root_env: Option<std::ffi::OsString>,
) -> Result<PathBuf> {
    if let Some(path) = plugin_root_env {
        let plugin_root = PathBuf::from(path);
        if is_claudix_plugin_root(&plugin_root) {
            return Ok(plugin_root);
        }
    }

    if is_claudix_plugin_root(project_root) {
        return Ok(local_plugin_root());
    }

    Err(ClaudixError::ConfigInvalid {
        message: "CLAUDE_PLUGIN_ROOT is not set".into(),
        recovery: RecoveryHint(
            "Run claudix install from the plugin directory or plugin environment",
        ),
    })
}

fn is_claudix_plugin_root(path: &Path) -> bool {
    let manifest_path = path.join(".claude-plugin").join("plugin.json");
    let Ok(manifest) = std::fs::read_to_string(manifest_path) else {
        return false;
    };

    manifest.contains("\"name\": \"claudix\"")
}

fn global_config_path() -> Result<PathBuf> {
    dirs::home_dir()
        .map(|home| home.join(".claude").join("claudix.toml"))
        .ok_or_else(|| ClaudixError::ConfigInvalid {
            message: "home directory is not available".into(),
            recovery: RecoveryHint("Set HOME before running claudix install"),
        })
}

fn require_git_repo(project_root: &Path) -> Result<()> {
    if !is_git_repo(project_root) {
        return Err(ClaudixError::NotAGitRepository {
            path: project_root.to_path_buf(),
            recovery: RecoveryHint("Run claudix index from inside a git repository"),
        });
    }
    Ok(())
}

pub fn is_git_repo(path: &Path) -> bool {
    let mut current = path;
    loop {
        if current.join(".git").exists() {
            return true;
        }
        match current.parent() {
            Some(parent) => current = parent,
            None => return false,
        }
    }
}

fn canonical_project_root(project_root: &Path) -> Result<PathBuf> {
    project_root.canonicalize().map_err(ClaudixError::from)
}

fn validate_search_query(query: &str) -> Result<()> {
    if query.trim().is_empty() {
        return Err(ClaudixError::ConfigInvalid {
            message: "search query cannot be empty".into(),
            recovery: RecoveryHint("Pass a non-empty search query"),
        });
    }
    Ok(())
}

fn validate_search_top_k(top_k: usize) -> Result<()> {
    if top_k == 0 {
        return Err(ClaudixError::ConfigInvalid {
            message: "top_k must be > 0".into(),
            recovery: RecoveryHint("Pass a positive top_k value"),
        });
    }

    Ok(())
}

fn parse_language_filter(language_filter: Option<Vec<String>>) -> Result<Option<Vec<Language>>> {
    let Some(language_filter) = language_filter else {
        return Ok(None);
    };
    if language_filter.is_empty() {
        return Ok(None);
    }

    let mut parsed = Vec::with_capacity(language_filter.len());
    for language in language_filter {
        parsed.push(parse_language(&language)?);
    }

    Ok(Some(parsed))
}

fn parse_path_prefix(path_prefix: Option<String>) -> Result<Option<RelativePath>> {
    let Some(prefix) = path_prefix else {
        return Ok(None);
    };
    let trimmed = prefix.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }

    validate_project_relative_path(Path::new(trimmed), "search.path_prefix")?;
    Ok(Some(RelativePath::new(trimmed.to_owned())))
}

fn parse_language(value: &str) -> Result<Language> {
    let value = value.trim();
    match value.to_ascii_lowercase().as_str() {
        "rust" => Ok(Language::Rust),
        "python" => Ok(Language::Python),
        "javascript" | "js" => Ok(Language::JavaScript),
        "typescript" | "ts" => Ok(Language::TypeScript),
        "go" => Ok(Language::Go),
        "java" => Ok(Language::Java),
        "c" => Ok(Language::C),
        "cpp" | "c++" => Ok(Language::Cpp),
        "unknown" => Ok(Language::Unknown),
        _ => Err(ClaudixError::ConfigInvalid {
            message: format!("unsupported language filter: {value}"),
            recovery: RecoveryHint(
                "Use one of: rust, python, javascript, typescript, go, java, c, cpp, unknown",
            ),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::embedding::{Provider, StubProvider};
    use crate::store::{Manifest, Store};
    use crate::types::Dimension;
    use tempfile::tempdir;

    mod fixture {
        include!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/common/fixture.rs"
        ));
    }

    mod test_support {
        use crate as claudix;

        include!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/common/test_support.rs"
        ));
    }

    use fixture::TestFixture;
    use test_support::{index_fixture, stub_config};

    struct CliHarness {
        _fixture: TestFixture,
        claudix: Claudix,
        store: Store,
    }

    fn test_claudix(project_root: PathBuf, config: Config) -> Result<Claudix> {
        let store = Store::new(&project_root, &config)?;
        let config = Arc::new(config);
        let embedder: Arc<dyn Provider> = Arc::new(StubProvider::with_model_id(
            config.embedding.model.clone(),
            Dimension(config.embedding.dimensions),
        ));

        Ok(Claudix::from_parts(project_root, config, embedder, store))
    }

    async fn cli_harness() -> Result<CliHarness> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        let claudix = test_claudix(fixture.root().to_path_buf(), config.clone())?;
        index_fixture(
            &claudix.store,
            claudix.embedder.as_ref(),
            claudix.project_root(),
            &config,
        )
        .await?;
        let store = Store::new(fixture.root(), &config)?;

        Ok(CliHarness {
            _fixture: fixture,
            claudix,
            store,
        })
    }

    #[cfg(unix)]
    #[test]
    fn watch_marker_install_refuses_live_foreign_pid() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let path = dir.path().join("watch.pid");
        let mut child = std::process::Command::new("sleep")
            .arg("60")
            .spawn()
            .ok()
            .unwrap_or_else(|| unreachable!());
        let foreign_pid = child.id();
        assert!(std::fs::write(&path, foreign_pid.to_string()).is_ok());

        let result = WatchMarkerGuard::install(path.clone());
        let stored_after = std::fs::read_to_string(&path).ok();
        let _ = child.kill();
        let _ = child.wait();

        assert!(
            matches!(result, Err(ClaudixError::Store(_))),
            "expected error when a live foreign PID owns the marker"
        );
        assert_eq!(
            stored_after.as_deref().map(str::trim),
            Some(foreign_pid.to_string().as_str()),
            "foreign marker contents must be untouched"
        );
    }

    #[test]
    fn watch_marker_install_clears_malformed_marker() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let path = dir.path().join("watch.pid");
        assert!(std::fs::write(&path, "not-a-pid").is_ok());

        let marker = WatchMarkerGuard::install(path.clone());
        assert!(marker.is_ok(), "malformed marker must be reclaimable");
    }

    #[test]
    fn watch_marker_install_takes_over_dead_pid() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let path = dir.path().join("watch.pid");
        // PID 0 is never running on Linux; use a guaranteed-dead value via crate helper.
        let dead_pid = pick_dead_pid();
        assert!(std::fs::write(&path, dead_pid.to_string()).is_ok());

        let marker = WatchMarkerGuard::install(path.clone());
        assert!(marker.is_ok(), "must reclaim a stale marker");
        let stored = std::fs::read_to_string(&path).ok();
        assert_eq!(
            stored.as_deref().map(str::trim),
            Some(std::process::id().to_string().as_str())
        );
    }

    #[test]
    fn watch_marker_install_adopts_handoff_with_own_pid() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let path = dir.path().join("watch.pid");
        assert!(std::fs::write(&path, std::process::id().to_string()).is_ok());

        let marker = WatchMarkerGuard::install(path.clone());
        assert!(marker.is_ok(), "must adopt parent's hand-off claim");
    }

    #[test]
    fn watch_marker_drop_leaves_foreign_pid_alone() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let path = dir.path().join("watch.pid");
        let marker = WatchMarkerGuard::install(path.clone())
            .ok()
            .unwrap_or_else(|| unreachable!());
        // Simulate another process reclaiming the marker before our drop runs.
        let foreign_pid = if std::process::id() == 1 { 2 } else { 1 };
        assert!(std::fs::write(&path, foreign_pid.to_string()).is_ok());

        drop(marker);
        assert!(
            path.exists(),
            "drop must not remove a marker reclaimed by another process"
        );
    }

    fn pick_dead_pid() -> u32 {
        for candidate in [9_999_999u32, 8_888_888, 7_777_777] {
            if !crate::store::process_running(candidate) {
                return candidate;
            }
        }
        9_999_999
    }

    #[test]
    fn parse_hook_event_accepts_known_values() {
        let event = parse_hook_event("SessionStart");
        assert!(matches!(event, Ok(HookEvent::SessionStart)));

        let event = parse_hook_event("PostToolUse");
        assert!(matches!(event, Ok(HookEvent::PostToolUse)));

        let event = parse_hook_event("PreToolUse");
        assert!(matches!(event, Ok(HookEvent::PreToolUse)));

        let event = parse_hook_event("UserPromptSubmit");
        assert!(matches!(event, Ok(HookEvent::UserPromptSubmit)));
    }

    #[test]
    fn parse_hook_event_rejects_unknown_values() {
        let result = parse_hook_event("Unknown");
        assert!(matches!(result, Err(ClaudixError::ConfigInvalid { .. })));
    }

    #[test]
    fn validate_search_query_rejects_empty_and_whitespace() {
        for query in ["", "   ", "\t", "\n"] {
            let result = validate_search_query(query);
            assert!(matches!(result, Err(ClaudixError::ConfigInvalid { .. })));
        }
    }

    #[test]
    fn validate_search_top_k_rejects_zero() {
        let result = validate_search_top_k(0);

        assert!(matches!(result, Err(ClaudixError::ConfigInvalid { .. })));
    }

    #[test]
    fn parse_language_filter_accepts_aliases() {
        let parsed = parse_language_filter(Some(vec!["rs".to_owned(), "ts".to_owned()]));
        assert!(parsed.is_err());

        let parsed = parse_language_filter(Some(vec![" rust ".to_owned(), "ts".to_owned()]));
        assert!(matches!(
            parsed,
            Ok(Some(ref languages)) if languages == &vec![Language::Rust, Language::TypeScript]
        ));
    }

    #[test]
    fn parse_language_filter_treats_empty_list_as_no_filter() {
        let parsed = parse_language_filter(Some(Vec::new()));

        assert!(matches!(parsed, Ok(None)));
    }

    #[test]
    fn parse_path_prefix_treats_blank_values_as_no_filter() {
        assert!(matches!(parse_path_prefix(None), Ok(None)));
        assert!(matches!(
            parse_path_prefix(Some("   ".to_owned())),
            Ok(None)
        ));
        assert_eq!(
            parse_path_prefix(Some(" src/math ".to_owned()))
                .ok()
                .flatten()
                .as_ref()
                .map(RelativePath::as_str),
            Some("src/math")
        );
    }

    #[test]
    fn parse_path_prefix_rejects_paths_outside_project() {
        for path_prefix in ["../src", "/tmp/src"] {
            let parsed = parse_path_prefix(Some(path_prefix.to_owned()));
            assert!(matches!(parsed, Err(ClaudixError::ConfigInvalid { .. })));
        }
    }

    #[tokio::test]
    async fn run_search_returns_ranked_hits() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output =
            run_search_with_claudix(&harness.claudix, "add".to_owned(), 5, None, None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(!output.hits.is_empty());
        assert_eq!(output.hits[0].name.as_deref(), Some("add"));
        assert_eq!(output.hits[0].file_path, "src/math.rs");
    }

    #[tokio::test]
    async fn run_search_applies_filters() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_search_with_claudix(
            &harness.claudix,
            "add".to_owned(),
            5,
            Some(vec!["rust".to_owned()]),
            Some(RelativePath::new("src/math").to_string()),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert_eq!(output.hits.len(), 1);
        assert_eq!(output.hits[0].file_path, "src/math.rs");
    }

    #[test]
    fn queue_reindex_paths_ignores_internal_state_paths() {
        let tmp = tempfile::tempdir();
        assert!(tmp.is_ok());
        let tmp = tmp.ok().unwrap_or_else(|| unreachable!());
        let root = tmp.path();
        let event = notify::Event {
            kind: EventKind::Modify(notify::event::ModifyKind::Data(
                notify::event::DataChange::Content,
            )),
            paths: vec![
                root.join("src/lib.rs"),
                root.join(".claudix/manifest.json"),
                root.join(".git/HEAD"),
            ],
            attrs: notify::event::EventAttributes::new(),
        };
        let filter = WatchFilter::load(root);
        assert!(filter.is_ok());
        let filter = filter.ok().unwrap_or_else(|| unreachable!());
        let mut pending = VecDeque::new();

        queue_reindex_paths(root, &filter, Ok(event), &mut pending);

        assert_eq!(
            pending.into_iter().collect::<Vec<_>>(),
            vec![PathBuf::from("src/lib.rs")]
        );
    }

    #[test]
    fn queue_reindex_paths_respects_project_gitignore() {
        let tmp = tempfile::tempdir();
        assert!(tmp.is_ok());
        let tmp = tmp.ok().unwrap_or_else(|| unreachable!());
        let root = tmp.path();
        assert!(std::fs::write(root.join(".gitignore"), "target/\nnode_modules/\n").is_ok());

        let event = notify::Event {
            kind: EventKind::Modify(notify::event::ModifyKind::Data(
                notify::event::DataChange::Content,
            )),
            paths: vec![
                root.join("src/lib.rs"),
                root.join("target/debug/build/foo"),
                root.join("node_modules/pkg/index.js"),
            ],
            attrs: notify::event::EventAttributes::new(),
        };
        let filter = WatchFilter::load(root);
        assert!(filter.is_ok());
        let filter = filter.ok().unwrap_or_else(|| unreachable!());
        let mut pending = VecDeque::new();

        queue_reindex_paths(root, &filter, Ok(event), &mut pending);

        assert_eq!(
            pending.into_iter().collect::<Vec<_>>(),
            vec![PathBuf::from("src/lib.rs")]
        );
    }

    #[test]
    fn drain_unique_paths_deduplicates_in_order() {
        let mut pending = VecDeque::from(vec![
            PathBuf::from("src/lib.rs"),
            PathBuf::from("src/lib.rs"),
            PathBuf::from("src/main.rs"),
        ]);

        assert_eq!(
            drain_unique_paths(&mut pending),
            vec![PathBuf::from("src/lib.rs"), PathBuf::from("src/main.rs")]
        );
    }

    #[test]
    fn clean_reindex_required_for_manifest_compatibility_errors() {
        assert!(requires_clean_reindex(&ClaudixError::SchemaMismatch {
            store: 0,
            binary: 1,
            recovery: RecoveryHint("reindex"),
        }));
        assert!(requires_clean_reindex(
            &ClaudixError::EmbeddingModelMismatch {
                store_model: "old".to_owned(),
                active_model: "new".to_owned(),
                recovery: RecoveryHint("reindex"),
            }
        ));
        assert!(requires_clean_reindex(&ClaudixError::DimensionMismatch {
            store_dim: 384,
            model_dim: 768,
            recovery: RecoveryHint("reindex"),
        }));
        assert!(!requires_clean_reindex(&ClaudixError::Store(
            "index already running".to_owned()
        )));
    }

    #[tokio::test]
    async fn run_index_clears_model_mismatch_and_reindexes() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let config = stub_config();
        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(&config);
        assert!(config_text.is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default(),
            )
            .is_ok()
        );

        let store = Store::new(fixture.root(), &config);
        assert!(store.is_ok());
        let store = store.ok().unwrap_or_else(|| unreachable!());
        let old_manifest = Manifest::new("old-model", config.embedding.dimensions);
        assert!(store.write_manifest(&old_manifest).is_ok());

        let output = run_index(fixture.root()).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());
        assert!(output.chunk_count > 0);

        let manifest = store.read_manifest();
        assert!(manifest.is_ok());
        let manifest = manifest.ok().unwrap_or_else(|| unreachable!());
        let manifest = manifest.unwrap_or_else(|| unreachable!());
        assert_eq!(manifest.embedding_model, config.embedding.model);
        assert_eq!(manifest.dimensions, config.embedding.dimensions);
        assert_eq!(manifest.chunk_count as usize, output.chunk_count);
    }

    #[tokio::test]
    async fn run_status_reports_manifest_and_counts() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let config = stub_config();
        let status = status_from_store(&harness.store, &config).await;
        assert!(status.is_ok());
        let status = status.ok().unwrap_or_else(|| unreachable!());

        assert_eq!(status.chunk_count, 3);
        assert_eq!(status.file_count, 2);
        assert_eq!(status.model.as_deref(), Some("stub-v1"));
        assert_eq!(status.dimensions, Some(8));
        assert!(!status.stale, "freshly indexed should not be stale");
    }

    #[tokio::test]
    async fn run_doctor_reports_index_and_embedding_health() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let config = stub_config();
        let claude_dir = harness.claudix.project_root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(&config);
        assert!(config_text.is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default(),
            )
            .is_ok()
        );

        let output = run_doctor(harness.claudix.project_root()).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(output.index_present);
        assert_eq!(output.chunk_count, 3);
        assert_eq!(output.file_count, 2);
        assert_eq!(output.model.as_deref(), Some("stub-v1"));
        assert_eq!(output.embedding_provider, "bundled");
        assert!(output.embedding_healthy);
    }

    #[tokio::test]
    async fn ensure_global_config_writes_default_once() {
        let temp = tempdir();
        assert!(temp.is_ok());
        let temp = temp.ok().unwrap_or_else(|| unreachable!());
        let config_path = temp.path().join(".claude").join("claudix.toml");

        let wrote_config = ensure_global_config(&config_path).await;
        assert!(wrote_config.is_ok());
        assert!(wrote_config.ok().unwrap_or(false));

        let contents = fs::read_to_string(&config_path).await;
        assert!(contents.is_ok());
        assert!(contents.ok().unwrap_or_default().contains("[embedding]"));

        let wrote_config = ensure_global_config(&config_path).await;
        assert!(wrote_config.is_ok());
        assert!(!wrote_config.ok().unwrap_or(true));
    }

    #[tokio::test]
    async fn install_copies_plugin_assets_into_plugin_root() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let plugin_root = fixture.root().join("plugin-root");

        let result =
            install_plugin_assets(Path::new(env!("CARGO_MANIFEST_DIR")), &plugin_root).await;
        assert!(result.is_ok());
        assert!(result.ok().unwrap_or(false));

        let second_result =
            install_plugin_assets(Path::new(env!("CARGO_MANIFEST_DIR")), &plugin_root).await;
        assert!(second_result.is_ok());
        assert!(!second_result.ok().unwrap_or(true));

        let plugin_manifest =
            fs::read_to_string(plugin_root.join(".claude-plugin").join("plugin.json")).await;
        assert!(plugin_manifest.is_ok());
        let plugin_manifest = plugin_manifest.ok().unwrap_or_default();
        assert!(plugin_manifest.contains("\"name\": \"claudix\""));
        assert!(plugin_manifest.contains("\"mcpServers\""));
        assert!(plugin_manifest.contains("\"command\": \"bash\""));
        assert!(plugin_manifest.contains("\"mcp\""));

        let hooks_manifest = fs::read_to_string(plugin_root.join("hooks").join("hooks.json")).await;
        assert!(hooks_manifest.is_ok());
        assert!(
            hooks_manifest
                .ok()
                .unwrap_or_default()
                .contains("scripts/session-start.sh")
        );

        let wrapper = fs::read_to_string(plugin_root.join("bin").join("claudix")).await;
        assert!(wrapper.is_ok());
        assert!(
            wrapper
                .ok()
                .unwrap_or_default()
                .contains("ensure-binary.sh")
        );

        let search_command =
            fs::read_to_string(plugin_root.join("commands").join("search.md")).await;
        assert!(search_command.is_ok());
        let search_command = search_command.ok().unwrap_or_default();
        assert!(search_command.contains("!`claudix search"));
        assert!(!search_command.contains("CLAUDE_PLUGIN_ROOT"));

        let ensure_script =
            fs::read_to_string(plugin_root.join("scripts").join("ensure-binary.sh")).await;
        assert!(ensure_script.is_ok());
        let ensure_script = ensure_script.ok().unwrap_or_default();
        assert!(ensure_script.contains("github.com"));
        assert!(ensure_script.contains("CLAUDE_PLUGIN_DATA"));
    }

    #[test]
    fn plugin_root_uses_claudix_environment_value_outside_local_checkout() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let env_root = fixture.root().join("env-plugin-root");
        assert!(std::fs::create_dir_all(env_root.join(".claude-plugin")).is_ok());
        assert!(
            std::fs::write(
                env_root.join(".claude-plugin").join("plugin.json"),
                "{\"name\": \"claudix\"}",
            )
            .is_ok()
        );
        let project_root = fixture.root().join("project");
        assert!(std::fs::create_dir_all(&project_root).is_ok());

        let result = plugin_root_from_env(&project_root, Some(env_root.clone().into_os_string()));
        assert!(result.is_ok());
        assert_eq!(result.ok().unwrap_or_default(), env_root);
    }

    #[test]
    fn plugin_root_ignores_foreign_environment_value() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        let result = plugin_root_from_env(root, Some(fixture.root().as_os_str().to_os_string()));
        assert!(result.is_ok());
        assert_eq!(
            result.ok().unwrap_or_default(),
            root.join("target").join("claudix-plugin")
        );
    }

    #[test]
    fn plugin_root_falls_back_to_local_manifest() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));

        let result = plugin_root_from_env(root, None);
        assert!(result.is_ok());
        assert_eq!(
            result.ok().unwrap_or_default(),
            root.join("target").join("claudix-plugin")
        );
    }

    #[test]
    fn plugin_root_requires_environment_or_local_manifest() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        let result = plugin_root_from_env(fixture.root(), None);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn setup_state_reports_missing_plugin_files() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        let setup_state = setup_state(fixture.root()).await;
        assert!(
            matches!(setup_state, SetupState::Missing(parts) if parts.contains(&"plugin files"))
        );
    }

    #[test]
    fn default_global_config_includes_commented_defaults() {
        let config = default_global_config();
        assert!(config.contains("[embedding]"));
        assert!(config.contains("provider = \"bundled\""));
        assert!(config.contains("reindex_after_hours = 24"));
        assert!(config.contains("[hooks]"));
        assert!(config.contains("intercept_grep = true"));
        assert!(config.contains("auto_reembed_on_edit = true"));
        assert!(config.contains("[search]"));
        assert!(config.contains("top_k = 10"));
    }
}