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
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
use std::ffi::OsStr;
use std::fs;
use std::path::Path;
use std::time::{Duration, SystemTime};

const WATCH_MARKER_FILE_NAME: &str = "watch.pid";
const WATCH_MARKER_STALE_SECS: u64 = 120;
const HEALTH_CACHE_FILE_NAME: &str = "embedder-health";
const HEALTH_CACHE_HEALTHY_TTL_SECS: u64 = 60;
const HEALTH_CACHE_UNHEALTHY_TTL_SECS: u64 = 30;
const PRE_TOOL_USE_TIMEOUT_MS: u64 = 1_500;
const PENDING_INDEX_READY_GRACE_SECS: u64 = 3;
const PENDING_INDEX_FAILURE_GRACE_SECS: u64 = 60;
const PENDING_INDEX_ACK_FILE_NAME: &str = "indexing-pending-acked";

use serde::Deserialize;
use serde_json::{Value, json};

use std::sync::Arc;

use crate::Claudix;
use crate::cli;
use crate::config::{self, Config};
use crate::error::{ClaudixError, Result};
use crate::search::SearchQuery;
use crate::store::{Manifest, Store};
use crate::util::{now_rfc3339, parse_rfc3339};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookEvent {
    SessionStart,
    PostToolUse,
    PreToolUse,
    UserPromptSubmit,
}

pub async fn run(project_root: &Path, event: HookEvent, payload: &str) -> Result<Option<Value>> {
    let payload: HookPayload = if payload.trim().is_empty() {
        HookPayload {
            tool_name: None,
            tool_input: None,
        }
    } else {
        serde_json::from_str(payload)?
    };

    match event {
        HookEvent::SessionStart => handle_session_start(project_root, payload).await,
        HookEvent::PostToolUse => handle_post_tool_use(project_root, payload).await,
        HookEvent::PreToolUse => handle_pre_tool_use(project_root, payload).await,
        HookEvent::UserPromptSubmit => handle_user_prompt_submit(project_root).await,
    }
}

fn is_git_repo(path: &Path) -> bool {
    cli::is_git_repo(path)
}

fn spawn_background_index(project_root: &Path, config: &crate::config::Config) -> bool {
    let Ok(store) = Store::new(project_root, config) else {
        return false;
    };
    if store.full_index_running() {
        return false;
    }
    if store.ensure_layout().is_err() {
        return false;
    }

    let marker_path = store.pending_index_marker_path();
    let manifest = store.read_manifest().ok().flatten();

    // Mismatched embedding model means the existing chunks have the wrong
    // dimension. Spawning `claudix index` without `--force` would either fail
    // or append vectors of a different shape — the user has to run
    // `claudix clear && claudix index` (or equivalent) themselves; the
    // session-start additionalContext already tells them so.
    if let Some(ref manifest) = manifest
        && manifest.chunk_count > 0
        && manifest.embedding_model != config.embedding.model
    {
        return false;
    }

    // Skip respawning when the existing index is fresh and populated. Without
    // this guard every SessionStart after the 60s marker window triggers a
    // full reindex of an unchanged repo.
    if let Some(ref manifest) = manifest
        && manifest.chunk_count > 0
        && !index_is_stale(manifest, config)
    {
        return false;
    }

    let prior_ts = manifest
        .as_ref()
        .and_then(|m| m.last_full_index_at.as_deref())
        .unwrap_or("none");

    // The marker doubles as the "spawn in progress" sentinel. `create_new`
    // serializes concurrent SessionStarts so we don't double-spawn before
    // the child has taken the full-index lock. A fresh marker from a prior
    // spawn means an index is already running (or just failed and hasn't
    // aged out yet); either way, leave it alone so its `created_at` keeps
    // anchoring the failure-grace clock.
    let placeholder = format!("{prior_ts}\n{}\n0\n", now_rfc3339());
    // Leave the ack file alone — `check_index_ready` rewrites it on success and
    // on each surfaced failure. Wiping it here would defeat dedup, so an index
    // that keeps failing with the same `prior_ts` would re-notify every session.
    if !try_claim_pending_index_marker(&marker_path, &placeholder) {
        return false;
    }

    let Some(child_pid) = spawn_detached_claudix(project_root, [OsStr::new("index")]) else {
        let _ = fs::remove_file(&marker_path);
        return false;
    };
    // Overwrite the placeholder with the spawned PID so `check_index_ready`
    // can gate the failure decision on the child still being alive — slow
    // ONNX cold loads or large config parses must not be misclassified as
    // a crashed index.
    let payload = format!("{prior_ts}\n{}\n{child_pid}\n", now_rfc3339());
    let _ = fs::write(&marker_path, payload);
    true
}

fn try_claim_pending_index_marker(marker_path: &Path, payload: &str) -> bool {
    use std::fs::OpenOptions;
    use std::io::Write;

    for _ in 0..2 {
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(marker_path)
        {
            Ok(mut file) => return file.write_all(payload.as_bytes()).is_ok(),
            Err(_) => {
                if pending_index_marker_is_fresh(marker_path) {
                    return false;
                }
                if fs::remove_file(marker_path).is_err() {
                    return false;
                }
            }
        }
    }
    false
}

fn pending_index_marker_is_fresh(marker_path: &Path) -> bool {
    let Some(marker) = read_pending_index_marker(marker_path) else {
        return false;
    };
    // `duration_since` errors when `created_at` is in the future — clock skew
    // or restore-from-backup. Treat that as expired so a single bad timestamp
    // can't permanently jam the auto-indexer.
    SystemTime::now()
        .duration_since(marker.created_at)
        .map(|age| age < Duration::from_secs(PENDING_INDEX_FAILURE_GRACE_SECS))
        .unwrap_or(false)
}

struct PendingIndexMarker {
    prior_ts: String,
    created_at: SystemTime,
    /// PID of the spawned `claudix index` child, or `None` if the marker is
    /// still the placeholder written before the child was forked (or a legacy
    /// marker missing this line entirely).
    child_pid: Option<u32>,
}

fn read_pending_index_marker(marker_path: &Path) -> Option<PendingIndexMarker> {
    let content = fs::read_to_string(marker_path).ok()?;
    let mut lines = content.lines();
    let prior_ts = lines.next()?.to_owned();
    let created_at = parse_rfc3339(lines.next()?).ok()?;
    let child_pid = lines
        .next()
        .and_then(|line| line.trim().parse::<u32>().ok())
        .filter(|pid| *pid != 0);
    Some(PendingIndexMarker {
        prior_ts,
        created_at,
        child_pid,
    })
}

fn spawn_detached_claudix<const N: usize, S>(project_root: &Path, args: [S; N]) -> Option<u32>
where
    S: AsRef<OsStr>,
{
    let binary = std::env::current_exe().ok()?;
    spawn_detached_command(project_root, binary.as_os_str(), args)
}

fn spawn_background_watch(project_root: &Path, config: &Config) -> bool {
    if !config.watch || !config.hooks.auto_reembed_on_edit {
        return false;
    }
    let Ok(store) = Store::new(project_root, config) else {
        return false;
    };
    if store.ensure_layout().is_err() {
        return false;
    }
    let marker_path = store.state_dir_path().join(WATCH_MARKER_FILE_NAME);
    let Some(mut marker_file) = try_claim_watch_marker(&marker_path) else {
        return false;
    };

    let Some(child_pid) = spawn_detached_claudix(project_root, [OsStr::new("watch")]) else {
        drop(marker_file);
        let _ = fs::remove_file(&marker_path);
        return false;
    };
    // Replace the placeholder claim with the spawned child PID so concurrent
    // SessionStarts see a live entry before the child finishes booting.
    use std::io::Write as _;
    let _ = marker_file.write_all(child_pid.to_string().as_bytes());
    true
}

/// Atomically reserve the watch marker for the duration of one watcher.
///
/// Returns the opened file handle on success so the caller can overwrite the
/// placeholder content with the spawned child PID. Returns `None` if a live
/// watcher already holds the marker. A stale marker is removed once and the
/// claim retried; persistent contention after retry returns `None`.
fn try_claim_watch_marker(marker_path: &Path) -> Option<std::fs::File> {
    use std::fs::OpenOptions;
    for _ in 0..2 {
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(marker_path)
        {
            Ok(file) => return Some(file),
            Err(_) => {
                if watch_marker_is_alive(marker_path) {
                    return None;
                }
                if fs::remove_file(marker_path).is_err() {
                    return None;
                }
            }
        }
    }
    None
}

fn watch_marker_is_alive(marker_path: &Path) -> bool {
    let Ok(content) = fs::read_to_string(marker_path) else {
        return false;
    };
    // PID liveness is the authoritative signal: a watcher that's been running
    // for hours is still alive even if its heartbeat task briefly stalled
    // past the mtime window. The earlier mtime-then-PID gate could declare a
    // long-running watcher dead and double-spawn it.
    if let Ok(pid) = content.trim().parse::<u32>() {
        return crate::store::process_running(pid);
    }
    // Unparseable content is the brief window between
    // `OpenOptions::create_new` and the parent writing the child PID. Fall
    // back to mtime so a fresh placeholder marker isn't treated as dead.
    let Ok(metadata) = fs::metadata(marker_path) else {
        return false;
    };
    let Ok(modified) = metadata.modified() else {
        return false;
    };
    SystemTime::now()
        .duration_since(modified)
        .map(|age| age < Duration::from_secs(WATCH_MARKER_STALE_SECS))
        .unwrap_or(false)
}

#[cfg(unix)]
fn spawn_detached_command<const N: usize, S>(
    project_root: &Path,
    binary: &OsStr,
    args: [S; N],
) -> Option<u32>
where
    S: AsRef<OsStr>,
{
    use std::os::unix::process::CommandExt;

    // `nohup` re-execs the binary, so its PID is the nohup process itself;
    // for our liveness checks that's fine because the wrapper stays alive
    // for the whole runtime of the child it execs into.
    std::process::Command::new("nohup")
        .arg(binary)
        .args(args.iter().map(AsRef::as_ref))
        .current_dir(project_root)
        .env("CLAUDE_PROJECT_DIR", project_root)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .process_group(0)
        .spawn()
        .ok()
        .map(|child| child.id())
}

#[cfg(windows)]
fn spawn_detached_command<const N: usize, S>(
    project_root: &Path,
    binary: &OsStr,
    args: [S; N],
) -> Option<u32>
where
    S: AsRef<OsStr>,
{
    use std::os::windows::process::CommandExt;

    const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
    const DETACHED_PROCESS: u32 = 0x0000_0008;

    std::process::Command::new(binary)
        .args(args.iter().map(AsRef::as_ref))
        .current_dir(project_root)
        .env("CLAUDE_PROJECT_DIR", project_root)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
        .spawn()
        .ok()
        .map(|child| child.id())
}

async fn handle_session_start(project_root: &Path, _payload: HookPayload) -> Result<Option<Value>> {
    let config = config::load(project_root).ok();

    let indexing_spawned = if let Some(ref config) = config
        && config.hooks.auto_index_on_session_start
        && is_git_repo(project_root)
    {
        spawn_background_index(project_root, config)
    } else {
        false
    };
    if let Some(ref config) = config
        && is_git_repo(project_root)
    {
        let _ = spawn_background_watch(project_root, config);
    }

    let store = config
        .as_ref()
        .and_then(|config| Store::new(project_root, config).ok());
    let manifest = store
        .as_ref()
        .and_then(|store| store.read_manifest().ok().flatten());
    // A spawn that lost the claim (another session already started one) still
    // counts as "in flight" for the user-facing message — otherwise we'd tell
    // them the index is empty while it's actively being built.
    let indexing_in_flight = indexing_spawned
        || store.as_ref().is_some_and(|store| {
            store.full_index_running() || store.pending_index_marker_path().exists()
        });

    let indexed_file_count = manifest.as_ref().map(|m| m.file_count).unwrap_or(0);
    let indexed_chunk_count = manifest.as_ref().map(|m| m.chunk_count).unwrap_or(0);
    let index_stale = match (&manifest, &config) {
        (Some(m), Some(c)) => index_is_stale(m, c),
        _ => indexed_chunk_count == 0,
    };
    let model_mismatch = match (&manifest, &config) {
        (Some(m), Some(c)) => m.embedding_model != c.embedding.model,
        _ => false,
    };

    let mut response = session_start_response(
        indexed_file_count,
        indexed_chunk_count,
        index_stale,
        model_mismatch,
        indexing_in_flight,
    );
    let user_message = session_start_message(cli::setup_state(project_root).await);
    if !user_message.is_empty() {
        response["systemMessage"] = Value::String(user_message);
    }
    Ok(Some(response))
}

fn session_start_message(setup_state: cli::SetupState) -> String {
    match setup_state {
        cli::SetupState::Ready => String::new(),
        cli::SetupState::Missing(parts) => format!(
            "claudix setup incomplete (missing {}); run the install script again",
            parts.join(", ")
        ),
    }
}

async fn handle_post_tool_use(project_root: &Path, payload: HookPayload) -> Result<Option<Value>> {
    let Some(tool_name) = payload.tool_name.as_deref() else {
        return Ok(None);
    };

    let config = config::load(project_root).ok();

    // Skip the per-edit spawn when a live watcher already covers file changes;
    // otherwise rapid edits fan out N detached `reindex-file` processes that
    // each cold-load ONNX before losing the in-process lock to the watcher.
    if is_write_tool(tool_name)
        && let Some(cfg) = config.as_ref()
        && cfg.hooks.auto_reembed_on_edit
        && !watcher_alive(project_root, cfg)
        && let Some(input) = payload.tool_input
        && let Some(file_path) = input.file_path.or(input.notebook_path)
    {
        spawn_background_reindex_file(project_root, &file_path);
    }

    Ok(config
        .as_ref()
        .and_then(|cfg| check_index_ready(project_root, cfg, "PostToolUse")))
}

async fn handle_user_prompt_submit(project_root: &Path) -> Result<Option<Value>> {
    let config = config::load(project_root).ok();
    Ok(config
        .as_ref()
        .and_then(|cfg| check_index_ready(project_root, cfg, "UserPromptSubmit")))
}

fn watcher_alive(project_root: &Path, config: &Config) -> bool {
    let Ok(store) = Store::new(project_root, config) else {
        return false;
    };
    let marker_path = store.state_dir_path().join(WATCH_MARKER_FILE_NAME);
    watch_marker_is_alive(&marker_path)
}

fn check_index_ready(project_root: &Path, config: &Config, event_name: &str) -> Option<Value> {
    let store = Store::new(project_root, config).ok()?;
    let marker_path = store.pending_index_marker_path();
    let ack_path = store.state_dir_path().join(PENDING_INDEX_ACK_FILE_NAME);
    let marker = read_pending_index_marker(&marker_path)?;

    // `created_at` in the future (clock skew, restored backup) would make
    // `duration_since` error forever; treat that as "past every grace window"
    // so the marker can be cleaned up instead of jamming the auto-indexer.
    let now = SystemTime::now();
    let age = match now.duration_since(marker.created_at) {
        Ok(age) => age,
        Err(_) => Duration::from_secs(PENDING_INDEX_FAILURE_GRACE_SECS),
    };
    if age < Duration::from_secs(PENDING_INDEX_READY_GRACE_SECS) {
        return None;
    }

    if store.full_index_running() {
        return None;
    }

    let manifest = store.read_manifest().ok().flatten();
    let current_ts = manifest
        .as_ref()
        .and_then(|m| m.last_full_index_at.as_deref())
        .unwrap_or("none");

    if current_ts != marker.prior_ts {
        let _ = fs::remove_file(&marker_path);
        let _ = fs::remove_file(&ack_path);
        let Some(manifest) = manifest else {
            // ts changed but the manifest is gone — treat as a failed run so
            // the user is informed instead of silently dropping the signal.
            return Some(indexing_failed_response(event_name));
        };
        return Some(json!({
            "hookSpecificOutput": {
                "hookEventName": event_name,
                "additionalContext": format!(
                    "claudix indexing complete — {} files, {} chunks. Semantic search is now ready: \
                     use search_code for conceptual queries, identifier lookups, and cross-file discovery.",
                    manifest.file_count, manifest.chunk_count
                ),
            }
        }));
    }

    // Manifest timestamp unchanged AND no index lock holder. If the spawned
    // child is still alive we're inside the slow-boot window (cold ONNX
    // load, large config parse) — never declare failure yet. Only after the
    // PID exits and the failure grace has elapsed do we surface a failure.
    if marker.child_pid.is_some_and(crate::store::process_running) {
        return None;
    }
    if age < Duration::from_secs(PENDING_INDEX_FAILURE_GRACE_SECS) {
        return None;
    }

    // Pre-first-index state has `prior_ts == "none"` indefinitely, so suppressing
    // duplicate-ts acks would silence every consecutive failure on a fresh repo.
    // Always surface failure for that sentinel; gate dedup on real timestamps.
    let is_first_index = marker.prior_ts == "none";
    let already_acked = !is_first_index
        && fs::read_to_string(&ack_path)
            .ok()
            .map(|content| content.trim() == marker.prior_ts)
            .unwrap_or(false);
    let _ = fs::write(&ack_path, &marker.prior_ts);
    let _ = fs::remove_file(&marker_path);

    if already_acked {
        return None;
    }

    Some(indexing_failed_response(event_name))
}

fn indexing_failed_response(event_name: &str) -> Value {
    json!({
        "hookSpecificOutput": {
            "hookEventName": event_name,
            "additionalContext":
                "claudix background indexing ended without updating the index — it may have failed. \
                 Run /claudix:doctor to diagnose.",
        }
    })
}

fn is_write_tool(tool_name: &str) -> bool {
    matches!(tool_name, "Edit" | "Write" | "NotebookEdit" | "MultiEdit")
}

fn spawn_background_reindex_file(project_root: &Path, file_path: &str) {
    spawn_detached_claudix(
        project_root,
        [OsStr::new("reindex-file"), OsStr::new(file_path)],
    );
}

async fn handle_pre_tool_use(project_root: &Path, payload: HookPayload) -> Result<Option<Value>> {
    // Hooks must fail open: a corrupt config or unreadable store yields a
    // passthrough, not a propagated error that could break the session.
    let Ok(config) = config::load(project_root) else {
        return Ok(None);
    };
    if !config.hooks.intercept_grep {
        return Ok(None);
    }

    let Some(tool_name) = payload.tool_name.as_deref() else {
        return Ok(None);
    };
    let Some(tool_input) = payload.tool_input else {
        return Ok(None);
    };

    let query = match tool_name {
        "Grep" => {
            if grep_input_has_scoping_flag(&tool_input) {
                return Ok(None);
            }
            tool_input.pattern
        }
        "Bash" => extract_search_command(tool_input.command.as_deref()),
        _ => None,
    };

    let Some(query) = query else {
        return Ok(None);
    };
    if should_passthrough(&query) {
        return Ok(None);
    }

    let Ok(store) = Store::new(project_root, &config) else {
        return Ok(None);
    };
    let Ok(Some(manifest)) = store.read_manifest() else {
        return Ok(None);
    };
    if index_is_stale(&manifest, &config) {
        return Ok(None);
    }
    if manifest.chunk_count == 0 {
        return Ok(None);
    }

    let health_cache_path = store.state_dir_path().join(HEALTH_CACHE_FILE_NAME);
    if matches!(read_cached_health(&health_cache_path), Some(false)) {
        return Ok(None);
    }

    let search_query = SearchQuery {
        query: query.clone(),
        top_k: config.search.top_k,
        language_filter: None,
        path_prefix: None,
    };
    let project_root = project_root.to_path_buf();
    let config_arc = Arc::new(config.clone());
    let work = async move {
        let claudix = Claudix::new(project_root, config_arc).await?;
        let results = claudix.search(search_query).await?;
        Ok::<_, ClaudixError>(results)
    };

    match tokio::time::timeout(Duration::from_millis(PRE_TOOL_USE_TIMEOUT_MS), work).await {
        Ok(Ok(results)) => {
            write_cached_health(&health_cache_path, true);
            if results.is_empty() {
                Ok(None)
            } else {
                Ok(Some(pre_tool_use_search_response(&query, results)))
            }
        }
        Ok(Err(_)) => {
            write_cached_health(&health_cache_path, false);
            Ok(None)
        }
        // Timeout doesn't necessarily mean the embedder is unhealthy — bundled
        // ONNX cold-loads can exceed the budget — so pass through without
        // poisoning the cache.
        Err(_) => Ok(None),
    }
}

fn read_cached_health(marker_path: &Path) -> Option<bool> {
    let metadata = fs::metadata(marker_path).ok()?;
    let modified = metadata.modified().ok()?;
    let age = SystemTime::now().duration_since(modified).ok()?;
    let content = fs::read_to_string(marker_path).ok()?;
    let healthy = match content.trim() {
        "1" => true,
        "0" => false,
        _ => return None,
    };
    let ttl = if healthy {
        HEALTH_CACHE_HEALTHY_TTL_SECS
    } else {
        HEALTH_CACHE_UNHEALTHY_TTL_SECS
    };
    (age < Duration::from_secs(ttl)).then_some(healthy)
}

fn write_cached_health(marker_path: &Path, healthy: bool) {
    let _ = fs::write(marker_path, if healthy { "1" } else { "0" });
}

fn session_start_response(
    file_count: u64,
    chunk_count: u64,
    stale: bool,
    model_mismatch: bool,
    indexing_in_flight: bool,
) -> Value {
    let additional_context = if model_mismatch {
        "claudix semantic search unavailable — embedding model mismatch. Run `claudix clear && claudix index` to rebuild.".to_owned()
    } else if chunk_count == 0 && indexing_in_flight {
        "claudix is building its first index in the background — search_code will report when ready. Use Grep or Read in the meantime.".to_owned()
    } else if chunk_count == 0 {
        "claudix is installed but the index is empty. Run /claudix:index to build it; until then use Grep or Read for code discovery.".to_owned()
    } else if indexing_in_flight {
        format!(
            "claudix semantic search ready — {file_count} files, {chunk_count} chunks (reindexing in background; you'll be notified when complete). \
             Use search_code for fast semantic search: conceptual queries, identifier lookups, cross-file discovery. \
             Use Grep for exact literals, regexes, or path-filtered scans."
        )
    } else if stale {
        format!(
            "claudix semantic search ready — {file_count} files, {chunk_count} chunks (index stale). \
             Use search_code for fast semantic search: conceptual queries, identifier lookups, cross-file discovery. \
             Use Grep for exact literals, regexes, or path-filtered scans."
        )
    } else {
        format!(
            "claudix semantic search ready — {file_count} files, {chunk_count} chunks. \
             Use search_code for fast semantic search: conceptual queries, identifier lookups, cross-file discovery. \
             Use Grep for exact literals, regexes, or path-filtered scans."
        )
    };
    json!({
        "hookSpecificOutput": {
            "hookEventName": "SessionStart",
            "additionalContext": additional_context,
        }
    })
}

fn pre_tool_use_search_response(query: &str, results: Vec<crate::search::SearchResult>) -> Value {
    let mut lines = vec![
        format!("claudix search results for '{query}':"),
        String::new(),
    ];
    for result in &results {
        let chunk = &result.chunk;
        let name_part = chunk
            .name
            .as_deref()
            .map(|n| format!(" {n}"))
            .unwrap_or_default();
        let stale_warning = if result.stale {
            " [STALE - file modified since index]"
        } else {
            ""
        };
        lines.push(format!(
            "{}:{}-{} [{}] {}{name_part} ({:.3}){}",
            chunk.file_path,
            chunk.line_range.start,
            chunk.line_range.end,
            chunk.language,
            chunk.kind,
            result.score,
            stale_warning,
        ));
        if !chunk.content.is_empty() {
            lines.push(truncate_snippet(&chunk.content, 20));
        }
        lines.push(String::new());
    }
    lines.push(
        "Tip: call search_code MCP tool directly next time to skip this interception round-trip."
            .to_owned(),
    );
    let context = lines.join("\n");
    json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": format!("claudix found {} semantic matches for '{query}' — see additionalContext.", results.len()),
            "additionalContext": context,
        }
    })
}

fn truncate_snippet(content: &str, max_lines: usize) -> String {
    let mut lines = content.lines();
    let taken: Vec<&str> = lines.by_ref().take(max_lines).collect();
    if lines.next().is_some() {
        format!("{}\n", taken.join("\n"))
    } else {
        taken.join("\n")
    }
}

fn extract_search_command(command: Option<&str>) -> Option<String> {
    let command = strip_command_prefixes(command?.trim());
    let args = command
        .strip_prefix("rg ")
        .or_else(|| command.strip_prefix("grep "))
        .or_else(|| command.strip_prefix("ag "))
        .or_else(|| command.strip_prefix("ack "))
        .or_else(|| command.strip_prefix("ripgrep "))
        .or_else(|| command.strip_prefix("git grep "))?;
    let args = args.trim();
    extract_quoted_pattern(args).or_else(|| extract_unquoted_pattern(args))
}

/// Strip wrappers like `time rg ...`, `nice rg ...`, or `env FOO=bar rg ...`
/// so the search-tool prefix matcher still finds `rg`/`grep`/etc.
fn strip_command_prefixes(command: &str) -> &str {
    const WRAPPERS: &[&str] = &["time ", "nice ", "stdbuf -oL ", "stdbuf -o0 "];
    let mut command = command;
    loop {
        let stripped = WRAPPERS
            .iter()
            .find_map(|prefix| command.strip_prefix(prefix));
        match stripped {
            Some(rest) => command = rest.trim_start(),
            None if command.starts_with("env ") => {
                // `env KEY=VAL KEY2=VAL2 rg ...`: skip the assignments until
                // we hit a non-assignment token (the actual command).
                let rest = command["env ".len()..].trim_start();
                let mut after_assignments = rest;
                for token in rest.split_whitespace() {
                    if token.contains('=') && !token.starts_with('=') {
                        after_assignments =
                            after_assignments.trim_start_matches(token).trim_start();
                    } else {
                        break;
                    }
                }
                command = after_assignments;
            }
            None => break,
        }
    }
    command
}

fn extract_quoted_pattern(args: &str) -> Option<String> {
    let bytes = args.as_bytes();
    let dq_pos = bytes.iter().position(|&b| b == b'"');
    let sq_pos = bytes.iter().position(|&b| b == b'\'');

    let (start, quote) = match (dq_pos, sq_pos) {
        (Some(d), Some(s)) => {
            if d < s {
                (d, b'"')
            } else {
                (s, b'\'')
            }
        }
        (Some(d), None) => (d, b'"'),
        (None, Some(s)) => (s, b'\''),
        (None, None) => return None,
    };

    let after = &args[start + 1..];
    let quote = char::from(quote);
    let mut pattern = String::new();
    let mut escaped = false;
    let mut closed = false;

    for character in after.chars() {
        if escaped {
            if character == quote {
                pattern.push(character);
            } else {
                pattern.push('\\');
                pattern.push(character);
            }
            escaped = false;
            continue;
        }

        if character == '\\' {
            escaped = true;
            continue;
        }

        if character == quote {
            closed = true;
            break;
        }

        pattern.push(character);
    }

    if escaped {
        pattern.push('\\');
    }
    if !closed {
        return None;
    }

    let pattern = pattern.trim();
    if pattern.is_empty() {
        None
    } else {
        Some(pattern.to_owned())
    }
}

fn extract_unquoted_pattern(args: &str) -> Option<String> {
    let tokens: Vec<&str> = args.split_whitespace().collect();
    if tokens.iter().any(|t| t.starts_with('-')) {
        return None;
    }
    let pattern_tokens: Vec<&str> = tokens
        .iter()
        .filter(|t| !t.contains('/') && !t.contains('\\'))
        .copied()
        .collect();
    if pattern_tokens.len() == 1 && !pattern_tokens[0].is_empty() {
        Some(pattern_tokens[0].to_owned())
    } else {
        None
    }
}

fn should_passthrough(query: &str) -> bool {
    let trimmed = query.trim();
    trimmed.is_empty()
        || looks_like_regex(trimmed)
        || looks_like_file_target(trimmed)
        || token_count(trimmed) < 3
}

fn looks_like_regex(query: &str) -> bool {
    query.contains('^')
        || query.contains('$')
        || query.contains('\\')
        || query.contains('[')
        || query.contains(']')
        || query.contains('(')
        || query.contains(')')
        || query.contains('+')
        || query.contains('?')
        || query.contains('{')
        || query.contains('}')
        || query.contains(".*")
}

fn looks_like_file_target(query: &str) -> bool {
    const FILE_EXTENSIONS: &[&str] = &[
        ".rs", ".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".java", ".c", ".h", ".cpp",
        ".cc", ".cxx", ".hpp", ".hxx", ".cs", ".sql",
    ];

    query.contains("--glob")
        || query.contains("--include")
        || query.contains("*.")
        || query.contains("src/")
        || FILE_EXTENSIONS.iter().any(|ext| query.contains(ext))
}

fn token_count(query: &str) -> usize {
    query
        .split(|character: char| !character.is_alphanumeric())
        .filter(|token| !token.is_empty())
        .count()
}

pub(crate) fn index_is_stale(manifest: &Manifest, config: &Config) -> bool {
    let Some(last_full_index_at) = manifest.last_full_index_at.as_deref() else {
        return true;
    };
    let Ok(last_full_index_at) = parse_rfc3339(last_full_index_at) else {
        return true;
    };
    let Ok(age) = SystemTime::now().duration_since(last_full_index_at) else {
        return false;
    };

    age > Duration::from_secs(config.indexing.reindex_after_hours.saturating_mul(3_600))
}

#[derive(Debug, Deserialize)]
struct HookPayload {
    tool_name: Option<String>,
    tool_input: Option<ToolInput>,
}

#[derive(Debug, Deserialize)]
struct ToolInput {
    file_path: Option<String>,
    notebook_path: Option<String>,
    pattern: Option<String>,
    command: Option<String>,
    path: Option<String>,
    include: Option<String>,
    glob: Option<String>,
    #[serde(rename = "type")]
    file_type: Option<String>,
    output_mode: Option<String>,
    head_limit: Option<Value>,
    #[serde(rename = "-A")]
    after_lines: Option<Value>,
    #[serde(rename = "-B")]
    before_lines: Option<Value>,
    #[serde(rename = "-C")]
    context_lines: Option<Value>,
    multiline: Option<bool>,
}

fn grep_input_has_scoping_flag(input: &ToolInput) -> bool {
    input.path.is_some()
        || input.include.is_some()
        || input.glob.is_some()
        || input.file_type.is_some()
        || input.output_mode.is_some()
        || input.head_limit.is_some()
        || input.after_lines.is_some()
        || input.before_lines.is_some()
        || input.context_lines.is_some()
        || input.multiline.is_some()
}

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

    #[test]
    fn looks_like_regex_detects_metacharacters() {
        for pattern in [
            "^pub fn",
            "fn\\s+\\w+",
            "[a-z]+",
            "fn(x)",
            "x+",
            "x?",
            "{3}",
            "x$",
            ".*",
        ] {
            assert!(
                looks_like_regex(pattern),
                "expected regex detection for: {pattern}"
            );
        }
        assert!(!looks_like_regex("error handling"));
        assert!(!looks_like_regex("handle_session_start"));
    }

    #[test]
    fn extract_search_command_handles_extra_tools_and_wrappers() {
        assert_eq!(
            extract_search_command(Some("git grep \"error handling\" -- src/")),
            Some("error handling".to_owned())
        );
        assert_eq!(
            extract_search_command(Some("time rg foo_bar")),
            Some("foo_bar".to_owned())
        );
        assert_eq!(
            extract_search_command(Some("nice rg \"some thing\"")),
            Some("some thing".to_owned())
        );
        assert_eq!(
            extract_search_command(Some("env FOO=1 BAR=2 rg target_pattern")),
            Some("target_pattern".to_owned())
        );
        assert_eq!(
            extract_search_command(Some("ack pattern")),
            Some("pattern".to_owned())
        );
        // Non-search command must still return None.
        assert_eq!(extract_search_command(Some("ls -la src/")), None);
    }

    #[test]
    fn looks_like_file_target_covers_all_supported_extensions() {
        for ext in &[
            ".rs", ".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".java", ".c", ".h", ".cpp",
            ".cc", ".cxx", ".hpp", ".hxx", ".cs", ".sql",
        ] {
            let query = format!("search routes{ext}");
            assert!(
                looks_like_file_target(&query),
                "expected passthrough for query containing {ext}"
            );
        }
        assert!(!looks_like_file_target("error handling retry logic"));
        assert!(looks_like_file_target("find *.rs files"));
        assert!(looks_like_file_target("search in src/"));
    }

    #[test]
    fn extract_unquoted_pattern_returns_sole_non_path_token() {
        assert_eq!(
            extract_unquoted_pattern("handle_session_start"),
            Some("handle_session_start".to_owned())
        );
        assert_eq!(
            extract_unquoted_pattern("handle_session_start src/"),
            Some("handle_session_start".to_owned())
        );
        // Multiple non-path tokens → ambiguous, return None.
        assert_eq!(extract_unquoted_pattern("foo bar"), None);
        // Any flag → bail out entirely (flag value might be misidentified as pattern).
        assert_eq!(
            extract_unquoted_pattern("--type rust handle_session_start"),
            None
        );
        // Path-only → None.
        assert_eq!(extract_unquoted_pattern("src/lib.rs"), None);
    }

    #[test]
    fn extract_quoted_pattern_uses_first_quote_type_as_delimiter() {
        // Single-quoted pattern containing double quotes — must extract the full inner string.
        assert_eq!(
            extract_quoted_pattern(r#"'say "hello"'"#),
            Some(r#"say "hello""#.to_owned())
        );
        // Double-quoted pattern (common case).
        assert_eq!(
            extract_quoted_pattern(r#""error handling""#),
            Some("error handling".to_owned())
        );
        // Double-quoted pattern with trailing flags.
        assert_eq!(
            extract_quoted_pattern(r#"-rn "pattern" src/"#),
            Some("pattern".to_owned())
        );
        assert_eq!(
            extract_quoted_pattern(r#""error \"quoted\" message" src/"#),
            Some(r#"error "quoted" message"#.to_owned())
        );
        // No quotes → None.
        assert_eq!(extract_quoted_pattern("add src/"), None);
    }
    use std::fs;
    use std::sync::Arc;
    use tempfile::tempdir;

    use crate::Claudix;
    use crate::config::Config;
    use crate::store::Manifest;

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

    mod config_support {
        use crate as claudix;

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

    use config_support::stub_config;
    use fixture::TestFixture;

    fn write_config(project_root: &Path, config: &Config) {
        let claude_dir = project_root.join(".claude");
        assert!(fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(config);
        assert!(config_text.is_ok());
        assert!(
            fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default()
            )
            .is_ok()
        );
    }

    #[tokio::test]
    async fn session_start_handles_empty_payload() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let response = run(fixture.root(), HookEvent::SessionStart, "").await;
        assert!(response.is_ok(), "empty payload must not error");
        assert!(response.ok().unwrap_or_else(|| unreachable!()).is_some());
    }

    #[tokio::test]
    async fn session_start_reports_incomplete_setup() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let mut config = stub_config();
        // Disable auto-index so the additionalContext assertion stays focused on
        // the empty-index state rather than the in-flight indexing message.
        config.hooks.auto_index_on_session_start = false;
        write_config(fixture.root(), &config);

        let response = run(fixture.root(), HookEvent::SessionStart, "{}").await;
        assert!(response.is_ok());
        let response = response.ok().unwrap_or_else(|| unreachable!());
        assert!(response.is_some());
        let response = response.unwrap_or(Value::Null);
        let user_message = response["systemMessage"].as_str().unwrap_or_default();
        assert!(user_message.contains("run the install script again"));

        let model_context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert_eq!(
            model_context,
            "claudix is installed but the index is empty. Run /claudix:index to build it; until then use Grep or Read for code discovery."
        );
    }

    #[test]
    fn session_start_message_reports_ready_setup() {
        assert_eq!(session_start_message(cli::SetupState::Ready), "");
        assert_eq!(
            session_start_message(cli::SetupState::Missing(vec!["bin"])),
            "claudix setup incomplete (missing bin); run the install script again"
        );
    }

    #[test]
    fn session_start_context_guides_tool_choice() {
        let response = session_start_response(42, 683, false, false, false);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();

        assert!(context.contains("Use search_code"));
        assert!(context.contains("fast semantic search"));
        assert!(context.contains("conceptual queries"));
        assert!(context.contains("identifier lookups"));
        assert!(context.contains("cross-file discovery"));
        assert!(context.contains("Use Grep for exact literals"));
    }

    #[tokio::test]
    async fn post_tool_use_spawns_background_reindex_and_returns_none() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let payload = json!({
            "tool_name": "Write",
            "tool_input": {
                "file_path": fixture.root().join("src/math.rs"),
            }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(response.ok().unwrap_or_else(|| unreachable!()).is_none());
    }

    #[tokio::test]
    async fn post_tool_use_ignores_read_tool() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let payload = json!({
            "tool_name": "Read",
            "tool_input": {
                "file_path": fixture.root().join("src/math.rs"),
            }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(
            response.ok().unwrap_or_else(|| unreachable!()).is_none(),
            "Read tool must not trigger reindex"
        );
    }

    #[tokio::test]
    async fn post_tool_use_triggers_reindex_for_notebook_edit() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        write_config(fixture.root(), &stub_config());

        let payload = json!({
            "tool_name": "NotebookEdit",
            "tool_input": {
                "notebook_path": fixture.root().join("analysis.ipynb"),
            }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        assert!(
            response.is_none(),
            "NotebookEdit must trigger reindex and return None"
        );
        Ok(())
    }

    #[tokio::test]
    async fn post_tool_use_passes_through_when_auto_reembed_disabled() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let mut config = stub_config();
        config.hooks.auto_reembed_on_edit = false;
        write_config(fixture.root(), &config);

        let payload = json!({
            "tool_name": "Write",
            "tool_input": {
                "file_path": fixture.root().join("src/math.rs"),
            }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(response.ok().unwrap_or_else(|| unreachable!()).is_none());
    }

    #[tokio::test]
    async fn pre_tool_use_denies_conceptual_grep_when_index_ready() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );

        let payload = json!({
            "tool_name": "Grep",
            "tool_input": {
                "pattern": "where is config loaded"
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        let response = response.ok().unwrap_or_else(|| unreachable!());
        assert!(response.is_some());
        let response = response.unwrap_or(Value::Null);
        assert_eq!(
            response["hookSpecificOutput"]["permissionDecision"],
            Value::String("deny".to_owned())
        );
    }

    #[tokio::test]
    async fn pre_tool_use_passes_regex_queries_through() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let payload = json!({
            "tool_name": "Grep",
            "tool_input": {
                "pattern": "^pub fn"
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(response.ok().unwrap_or_else(|| unreachable!()).is_none());
    }

    #[tokio::test]
    async fn pre_tool_use_passes_conceptual_bash_rg_when_search_returns_no_results() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );

        // "where is the config loaded" is conceptual but the small_rust fixture has no config code;
        // semantic search returns empty → must pass through, not block grep with no alternative.
        let payload = json!({
            "tool_name": "Bash",
            "tool_input": {
                "command": "rg \"where is the config loaded\""
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(
            response.ok().unwrap_or_else(|| unreachable!()).is_none(),
            "must pass through when semantic search has no results to offer"
        );
    }

    #[tokio::test]
    async fn pre_tool_use_passes_bash_rg_with_path_arg_through_when_no_conceptual_pattern() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );

        // Unquoted single-word pattern — extracted but token_count < 3 so passes through.
        let payload = json!({
            "tool_name": "Bash",
            "tool_input": {
                "command": "rg add src/"
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(
            response.ok().unwrap_or_else(|| unreachable!()).is_none(),
            "unquoted single-word rg command should pass through"
        );
    }

    #[tokio::test]
    async fn pre_tool_use_intercepts_unquoted_identifier_in_bash_rg() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );

        // Unquoted identifier with enough tokens — should be intercepted just like a quoted query.
        let payload = json!({
            "tool_name": "Bash",
            "tool_input": {
                "command": "rg add_two_numbers"
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        let response = response.ok().unwrap_or_else(|| unreachable!());
        assert!(
            response.is_some(),
            "unquoted multi-token identifier should be intercepted"
        );
        let response = response.unwrap_or(Value::Null);
        assert_eq!(
            response["hookSpecificOutput"]["permissionDecision"],
            Value::String("deny".to_owned())
        );
    }

    #[tokio::test]
    async fn pre_tool_use_passes_bash_rg_with_regex_pattern_through() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );

        let payload = json!({
            "tool_name": "Bash",
            "tool_input": {
                "command": "rg \"^pub fn\" src/"
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(
            response.ok().unwrap_or_else(|| unreachable!()).is_none(),
            "regex pattern in rg command should pass through"
        );
    }

    #[tokio::test]
    async fn pre_tool_use_passes_conceptual_bash_rg_with_path_arg_when_no_results() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );

        // Conceptual query with a path arg: semantic search still finds nothing for "config loaded"
        // in the small_rust fixture → must pass through.
        let payload = json!({
            "tool_name": "Bash",
            "tool_input": {
                "command": "rg \"where is the config loaded\" src/"
            }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        assert!(
            response.ok().unwrap_or_else(|| unreachable!()).is_none(),
            "must pass through when semantic search has no results to offer"
        );
    }

    #[tokio::test]
    async fn pre_tool_use_returns_search_results_in_context() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        write_config(fixture.root(), &stub_config());

        let claudix = Claudix::new(fixture.root().to_path_buf(), Arc::new(stub_config())).await;
        assert!(claudix.is_ok());
        assert!(
            claudix
                .ok()
                .unwrap_or_else(|| unreachable!())
                .index_full()
                .await
                .is_ok()
        );
        assert!(
            std::fs::write(
                fixture.root().join("src/math.rs"),
                "pub fn subtract(left: i32, right: i32) -> i32 { left - right }\n",
            )
            .is_ok()
        );

        let payload = json!({
            "tool_name": "Grep",
            "tool_input": { "pattern": "add two numbers together" }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await;
        assert!(response.is_ok());
        let response = response.ok().unwrap_or_else(|| unreachable!());
        assert!(response.is_some());
        let response = response.unwrap_or(Value::Null);

        assert_eq!(
            response["hookSpecificOutput"]["permissionDecision"],
            Value::String("deny".to_owned())
        );
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("claudix search results"),
            "hook must embed search results in context, got: {context}"
        );
        assert!(
            context.contains("src/"),
            "context must include file paths from search results"
        );
        assert!(
            context.contains("[STALE - file modified since index]"),
            "context must warn about stale hits, got: {context}"
        );
        assert!(
            context.contains("search_code MCP tool"),
            "context must include tip to use search_code directly, got: {context}"
        );
    }

    #[test]
    fn pending_index_marker_round_trips() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join("indexing-pending");
        let payload = format!("2026-04-20T00:00:00Z\n{}\n42\n", now_rfc3339());

        assert!(try_claim_pending_index_marker(&marker_path, &payload));
        let marker = read_pending_index_marker(&marker_path);
        assert!(marker.is_some());
        let marker = marker.unwrap_or_else(|| unreachable!());
        assert_eq!(marker.prior_ts, "2026-04-20T00:00:00Z");
        assert_eq!(marker.child_pid, Some(42));
    }

    #[test]
    fn pending_index_marker_treats_zero_pid_as_placeholder() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join("indexing-pending");
        let payload = format!("none\n{}\n0\n", now_rfc3339());
        assert!(try_claim_pending_index_marker(&marker_path, &payload));
        let marker = read_pending_index_marker(&marker_path).unwrap_or_else(|| unreachable!());
        assert_eq!(marker.child_pid, None);
    }

    #[test]
    fn pending_index_marker_claim_is_atomic() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join("indexing-pending");
        let first = format!("none\n{}\n", now_rfc3339());
        assert!(try_claim_pending_index_marker(&marker_path, &first));

        // Second claim while the first is still fresh must fail.
        let second = format!("ts-2\n{}\n", now_rfc3339());
        assert!(!try_claim_pending_index_marker(&marker_path, &second));
        let marker = read_pending_index_marker(&marker_path).unwrap_or_else(|| unreachable!());
        assert_eq!(marker.prior_ts, "none", "first claim must remain in place");
    }

    #[test]
    fn watch_marker_with_dead_pid_is_not_alive() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join(WATCH_MARKER_FILE_NAME);
        // PID 0 never refers to a real process on Unix or Windows, so this
        // exercises the "parsed PID but process is gone" branch.
        fs::write(&marker_path, "0").unwrap_or_else(|_| unreachable!());

        assert!(
            !watch_marker_is_alive(&marker_path),
            "watch marker with dead PID must be reclaimable"
        );
    }

    #[test]
    fn watch_marker_with_live_pid_ignores_mtime() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join(WATCH_MARKER_FILE_NAME);
        fs::write(&marker_path, std::process::id().to_string()).unwrap_or_else(|_| unreachable!());

        let file = fs::OpenOptions::new()
            .write(true)
            .open(&marker_path)
            .unwrap_or_else(|_| unreachable!());
        // Past mtime that would have flunked the old stale-window gate — PID
        // liveness is now authoritative so the watcher must still register alive.
        let stale = SystemTime::now() - Duration::from_secs(WATCH_MARKER_STALE_SECS * 10);
        file.set_modified(stale).unwrap_or_else(|_| unreachable!());
        drop(file);

        assert!(
            watch_marker_is_alive(&marker_path),
            "watch marker with live PID must stay alive regardless of mtime"
        );
    }

    #[test]
    fn pending_index_marker_with_future_timestamp_is_not_fresh() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join("indexing-pending");
        // 1 hour in the future — simulates clock skew / backup restore.
        let future = SystemTime::now() + Duration::from_secs(3_600);
        let future_ts = crate::util::format_rfc3339(future);
        fs::write(&marker_path, format!("none\n{future_ts}\n0\n"))
            .unwrap_or_else(|_| unreachable!());

        assert!(
            !pending_index_marker_is_fresh(&marker_path),
            "future-timestamped marker must be reclaimable"
        );
    }

    #[test]
    fn pending_index_marker_claim_replaces_legacy_or_unparseable() {
        let dir = tempdir().ok().unwrap_or_else(|| unreachable!());
        let marker_path = dir.path().join("indexing-pending");
        assert!(fs::write(&marker_path, "legacy-single-line").is_ok());

        let payload = format!("none\n{}\n", now_rfc3339());
        assert!(try_claim_pending_index_marker(&marker_path, &payload));
        let marker = read_pending_index_marker(&marker_path);
        assert!(marker.is_some());
    }

    #[tokio::test]
    async fn check_index_ready_resurfaces_failure_for_first_index_sentinel() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        write_config(fixture.root(), &config);
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;

        // Pre-ack the "none" sentinel so a naive dedup check would suppress.
        let ack_path = store.state_dir_path().join(PENDING_INDEX_ACK_FILE_NAME);
        fs::write(&ack_path, "none")?;

        let stale_created_at = "2025-01-01T00:00:00Z";
        let payload = format!("none\n{stale_created_at}\n0\n");
        fs::write(store.pending_index_marker_path(), payload)?;

        let response = check_index_ready(fixture.root(), &config, "PostToolUse");
        let response = response.unwrap_or(Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("ended without updating the index"),
            "repeat failures before the first successful index must still surface, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn user_prompt_submit_surfaces_indexing_completion() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        write_config(fixture.root(), &config);
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;

        // Marker says the prior index timestamp was "none"; the manifest now
        // has a fresh successful timestamp, so the handler must surface the
        // completion message even though no write tool fired.
        let stale_created_at = "2025-01-01T00:00:00Z";
        let payload = format!("none\n{stale_created_at}\n0\n");
        fs::write(store.pending_index_marker_path(), payload)?;
        let mut manifest = Manifest::new(config.embedding.model.clone(), 8);
        manifest.file_count = 3;
        manifest.chunk_count = 12;
        manifest.last_full_index_at = Some(crate::util::now_rfc3339());
        store.write_manifest(&manifest)?;

        let response = run(fixture.root(), HookEvent::UserPromptSubmit, "{}").await?;
        let response = response.unwrap_or(Value::Null);
        assert_eq!(
            response["hookSpecificOutput"]["hookEventName"].as_str(),
            Some("UserPromptSubmit"),
            "response must carry the firing event name"
        );
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("indexing complete"),
            "expected completion context, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn check_index_ready_defers_failure_while_child_pid_alive() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        write_config(fixture.root(), &config);
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;

        // Backdate the marker past the failure grace but record this test
        // process as the spawned child — `check_index_ready` must defer the
        // failure decision while that PID is still alive.
        let stale_created_at = "2025-01-01T00:00:00Z";
        let my_pid = std::process::id();
        let payload = format!("none\n{stale_created_at}\n{my_pid}\n");
        fs::write(store.pending_index_marker_path(), payload)?;

        let response = check_index_ready(fixture.root(), &config, "PostToolUse");
        assert!(
            response.is_none(),
            "must not declare failure while spawned child is alive"
        );
        assert!(
            store.pending_index_marker_path().exists(),
            "marker must survive the deferred decision"
        );
        Ok(())
    }

    #[tokio::test]
    async fn check_index_ready_surfaces_failure_when_manifest_is_missing() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        write_config(fixture.root(), &config);
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;

        // Backdate the marker past the failure grace; leave the manifest absent
        // to simulate a first-time index that crashed before writing one.
        let stale_created_at = "2025-01-01T00:00:00Z";
        let payload = format!("none\n{stale_created_at}\n");
        fs::write(store.pending_index_marker_path(), payload)?;

        let response = check_index_ready(fixture.root(), &config, "PostToolUse");
        let response = response.unwrap_or(Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("ended without updating the index"),
            "expected failure context, got: {context}"
        );
        assert!(
            !store.pending_index_marker_path().exists(),
            "marker must be cleaned up after surfacing failure"
        );
        Ok(())
    }

    #[test]
    fn stale_index_detection_respects_threshold() {
        let mut config = stub_config();
        config.indexing.reindex_after_hours = 24;
        let mut manifest = Manifest::new("stub-v1", 8);
        manifest.last_full_index_at = Some("2026-04-20T00:00:00Z".to_owned());
        assert!(index_is_stale(&manifest, &config));
    }

    #[test]
    fn fresh_index_detection_allows_recent_manifest() {
        let project_root = tempdir();
        assert!(project_root.is_ok());
        let _project_root = project_root.ok().unwrap_or_else(|| unreachable!());
        let mut config = stub_config();
        config.indexing.reindex_after_hours = 24 * 365 * 20;
        let mut manifest = Manifest::new("stub-v1", 8);
        manifest.last_full_index_at = Some(crate::util::now_rfc3339());
        assert!(!index_is_stale(&manifest, &config));
    }

    #[tokio::test]
    async fn spawn_background_index_skips_when_manifest_fresh_and_populated() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        write_config(fixture.root(), &config);

        Claudix::new(fixture.root().to_path_buf(), Arc::new(config.clone()))
            .await?
            .index_full()
            .await?;

        let store = Store::new(fixture.root(), &config)?;
        let marker_path = store.pending_index_marker_path();
        let _ = fs::remove_file(&marker_path);

        assert!(
            !spawn_background_index(fixture.root(), &config),
            "fresh non-empty matching-model index must not respawn"
        );
        assert!(
            !marker_path.exists(),
            "no pending marker should be written when spawn is skipped"
        );
        Ok(())
    }

    #[tokio::test]
    async fn session_start_reports_indexing_in_flight_when_marker_exists() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let mut config = stub_config();
        config.hooks.auto_index_on_session_start = false;
        write_config(fixture.root(), &config);

        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;
        let payload = format!("none\n{}\n0\n", now_rfc3339());
        fs::write(store.pending_index_marker_path(), payload)?;

        let response = run(fixture.root(), HookEvent::SessionStart, "{}").await?;
        let response = response.unwrap_or(Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("building its first index"),
            "expected in-flight message for empty manifest with pending marker, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn pre_tool_use_passes_through_on_corrupt_config() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let claude_dir = fixture.root().join(".claude");
        fs::create_dir_all(&claude_dir)?;
        // Malformed TOML — config::load would error; the hook must fail open.
        fs::write(
            claude_dir.join("claudix.toml"),
            "this is = not = valid toml [",
        )?;

        let payload = json!({
            "tool_name": "Grep",
            "tool_input": { "pattern": "where is config loaded" }
        });
        let response = run(fixture.root(), HookEvent::PreToolUse, &payload.to_string()).await?;
        assert!(
            response.is_none(),
            "corrupt config must passthrough, not error"
        );
        Ok(())
    }

    #[tokio::test]
    async fn watcher_alive_reports_live_marker() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;
        let marker_path = store.state_dir_path().join(WATCH_MARKER_FILE_NAME);
        fs::write(&marker_path, std::process::id().to_string())?;

        assert!(
            watcher_alive(fixture.root(), &config),
            "current-PID watch marker must register as alive"
        );
        Ok(())
    }

    #[tokio::test]
    async fn watcher_alive_returns_false_without_marker() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        assert!(!watcher_alive(fixture.root(), &config));
        Ok(())
    }

    #[tokio::test]
    async fn spawn_background_index_runs_when_manifest_missing() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        write_config(fixture.root(), &config);

        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;

        assert!(
            spawn_background_index(fixture.root(), &config),
            "missing manifest must trigger a spawn"
        );
        Ok(())
    }
}