claudix 0.2.0

Local semantic search plugin for Claude Code
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
use std::path::Path;
use std::time::Duration;

use serde_json::{Value, json};

use crate::config::{self, Config};
use crate::enumeration::WatchFilter;
use crate::error::Result;
use crate::prompts;
use crate::search::neighbors::neighbors;
use crate::store::Store;
use crate::store::marker::change_neighbors;
use crate::types::RelativePath;

use super::payload::{HookPayload, ToolInput};
use super::ready_check::check_index_ready;
use super::spawn::spawn_background_reindex_file;
use crate::store::marker::WATCH_MARKER_STALE_SECS;

/// Fail-open budget for the read-time surfacing load + cosine scan. The `Read`
/// hook must not stall the session, so the whole-corpus read and O(n²) scan are
/// each capped at this; on elapse the hook surfaces nothing.
const READ_SURFACING_TIMEOUT_MS: u64 = 2_000;

/// Corpus ceiling for read-time surfacing. Above this the O(n²) scan is too
/// expensive to run on the hot `Read` path, so surfacing is skipped entirely.
const READ_SURFACING_MAX_CHUNKS: usize = 50_000;

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

    // `Read` rides this hook too (see hooks.json matcher) purely for read-time
    // surfacing — it must NEVER spawn a reindex. The edit tools below do.
    let tool_name = payload.tool_name.as_deref();

    if tool_name == Some("Read")
        && !config
            .as_ref()
            .is_some_and(|cfg| cfg.hooks.surface_related_on_read)
    {
        return Ok(None);
    }

    // Spawn a background reindex only when an edit tool fired on a real file.
    // The ready-check and neighbor-surfacing runs on every PostToolUse event
    // regardless of whether a spawn happened.
    //
    // Multi-file payloads (MultiEdit-style tools) may carry `files_modified`
    // in addition to or instead of `file_path`. Collect all distinct paths,
    // dedupe, and spawn one reindex per watchable file.
    let read_input = if let Some(name) = tool_name
        && matches!(name, "Edit" | "Write" | "NotebookEdit" | "MultiEdit")
        && let Some(cfg) = config.as_ref()
        && cfg.hooks.auto_reembed_on_edit
        && !watcher_alive(project_root, cfg)
        && let Some(input) = payload.tool_input.as_ref()
    {
        let paths = reindex_paths_from_input(project_root, input);
        let spawned = paths
            .iter()
            .filter(|p| reindex_target_is_watchable(project_root, p))
            .inspect(|p| spawn_background_reindex_file(project_root, p))
            .count();
        // Preserve tool_input for read-surfacing only when nothing was spawned
        // (no watchable paths found). When we did spawn, pass None so the
        // read-surfacing branch correctly skips (it only acts on Read events).
        if spawned > 0 {
            None
        } else {
            payload.tool_input
        }
    } else {
        payload.tool_input
    };

    // Prefer not to drop any message: index-ready, change-neighbors, and
    // read-neighbors are all surfaced together. Index-ready goes first (most
    // urgent); the rest append in order.
    let index_ready = config
        .as_ref()
        .and_then(|cfg| check_index_ready(project_root, cfg, "PostToolUse"));

    let change_neighbors =
        take_change_neighbors_context(project_root, config.as_ref(), "PostToolUse");

    let read_neighbors = read_surfacing_context(
        project_root,
        config.as_ref(),
        tool_name,
        read_input.as_ref(),
        "PostToolUse",
    )
    .await;

    Ok(combine_hook_responses(
        "PostToolUse",
        [index_ready, change_neighbors, read_neighbors],
    ))
}

/// Surface code semantically related to a ranged `Read`.
///
/// Fast flag-off path: when `surface_related_on_read` is false (the default),
/// this returns before any store read or cosine scan — flag-off users pay only
/// the process spawn + config load this hook costs.
///
/// Range semantics: `start = offset.unwrap_or(1)`; `end` is `offset + limit - 1`
/// when `limit` is present, else open-ended (window runs to EOF). A chunk's
/// `[line_start, line_end]` overlaps the window when it starts at or before
/// `end` (if bounded) and ends at or after `start`. A full-file read (neither
/// `offset` nor `limit`) is a deliberate noop — surfacing is tied to a focused
/// region the agent narrowed to.
///
/// Reuses [`neighbors`] over the read file's stored vectors — no embedding call.
/// Fail-open: any error behaves as a noop.
async fn read_surfacing_context(
    project_root: &Path,
    config: Option<&Config>,
    tool_name: Option<&str>,
    tool_input: Option<&ToolInput>,
    event_name: &str,
) -> Option<Value> {
    if tool_name != Some("Read") {
        return None;
    }
    let cfg = config?;
    if !cfg.hooks.surface_related_on_read {
        return None;
    }

    let input = tool_input?;
    let file_path = input.file_path.as_deref()?;
    // Full-file read (no offset/limit) → noop.
    if input.offset.is_none() && input.limit.is_none() {
        return None;
    }

    // Claude Code typically sends absolute paths. Strip the project root to get
    // a relative path so it matches what the store indexes. Reject anything that
    // escapes the project root (absolute path outside the root, or `..` traversal).
    let raw = Path::new(file_path);
    let relative = if raw.is_absolute() {
        let raw_canonical = raw.canonicalize();
        let raw_absolute = raw_canonical.as_deref().unwrap_or(raw);
        let root_canonical = project_root.canonicalize();
        let root_absolute = root_canonical.as_deref().unwrap_or(project_root);
        raw_absolute.strip_prefix(root_absolute).ok()?.to_path_buf()
    } else {
        raw.to_path_buf()
    };
    let read_path = RelativePath::from_path(&relative);
    read_path
        .reject_escape(prompts::hints::READ_INSIDE_PROJECT_DIR)
        .ok()?;

    let start = input.offset.unwrap_or(1);
    let end = input
        .limit
        .map(|count| start.saturating_add(count.saturating_sub(1)));

    let store = Store::new(project_root, cfg).ok()?;
    // Read-time surfacing rides the hot `Read` path. `read_chunks` deserializes
    // every vector and the cosine scan is O(n²); on a large repo (or while a full
    // reindex holds the write lock) either can block for seconds and stall the
    // session. Bound the whole load+scan in a timeout and skip outright when the
    // corpus is too large to scan cheaply. Fail-open: any elapse/error → noop.
    let all_rows = match tokio::time::timeout(
        Duration::from_millis(READ_SURFACING_TIMEOUT_MS),
        store.read_chunks(),
    )
    .await
    {
        Ok(Ok(rows)) => rows,
        _ => return None,
    };
    if all_rows.len() > READ_SURFACING_MAX_CHUNKS {
        return None;
    }

    let query_vectors: Vec<Vec<f32>> = all_rows
        .iter()
        .filter(|row| row.file_path == read_path.as_str())
        .filter(|row| chunk_overlaps_window(row.line_start, row.line_end, start, end))
        .map(|row| row.vector.clone())
        .collect();
    if query_vectors.is_empty() {
        return None;
    }

    let exclude = read_path.clone();
    let top_k = cfg.hooks.related_top_k;
    let min_similarity = cfg.hooks.related_min_similarity;
    let hits = match tokio::time::timeout(
        Duration::from_millis(READ_SURFACING_TIMEOUT_MS),
        tokio::task::spawn_blocking(move || {
            neighbors(&all_rows, &query_vectors, &exclude, top_k, min_similarity)
        }),
    )
    .await
    {
        Ok(Ok(hits)) => hits,
        _ => return None,
    };
    // Defense in depth on top of index-time pruning: a file deleted out-of-band
    // may still have chunks in the store until the next reindex, so never offer
    // a now-missing file as related code. Cheap: one stat per hit (≤ top_k).
    let hits: Vec<_> = hits
        .into_iter()
        .filter(|n| neighbor_file_exists(project_root, &n.file_path))
        .collect();
    if hits.is_empty() {
        return None;
    }

    let locations: Vec<String> = hits
        .iter()
        .map(|n| {
            prompts::hooks::read_neighbor_line(
                &n.file_path,
                n.line_start,
                n.line_end,
                n.name.as_deref(),
                n.score,
            )
        })
        .collect();

    let context = prompts::hooks::read_related_context(read_path.as_str(), start, end, &locations);

    Some(json!({
        "hookSpecificOutput": {
            "hookEventName": event_name,
            "additionalContext": context,
        }
    }))
}

/// Whether a neighbor's repo-relative file still exists on disk. Guards against
/// surfacing stale chunks for files deleted since they were indexed, and rejects
/// a poisoned/legacy row whose stored path escapes the project root (an absolute
/// path or `..` traversal) so it never yields a filesystem existence oracle
/// outside the project or a misleading agent-visible "related code" path.
fn neighbor_file_exists(project_root: &Path, relative_path: &str) -> bool {
    let relative = RelativePath::new(relative_path);
    if relative
        .reject_escape(prompts::hints::READ_INSIDE_PROJECT_DIR)
        .is_err()
    {
        return false;
    }
    project_root.join(relative.as_str()).exists()
}

/// Whether a chunk's inclusive `[chunk_start, chunk_end]` line span overlaps the
/// read window `[window_start, window_end]`. `window_end == None` is open-ended
/// (runs to EOF), so only the lower bound constrains the chunk.
fn chunk_overlaps_window(
    chunk_start: u32,
    chunk_end: u32,
    window_start: u32,
    window_end: Option<u32>,
) -> bool {
    let starts_in_range = window_end.is_none_or(|end| chunk_start <= end);
    starts_in_range && chunk_end >= window_start
}

/// Read and ack the change-neighbors marker, returning formatted additionalContext.
/// Returns `None` when the marker is absent, feature is disabled, or the store
/// cannot be constructed (fail-open).
pub(super) fn take_change_neighbors_context(
    project_root: &Path,
    config: Option<&Config>,
    event_name: &str,
) -> Option<Value> {
    let cfg = config?;
    if !cfg.hooks.surface_related_on_edit {
        return None;
    }
    let store = Store::new(project_root, cfg).ok()?;
    let marker_path = store.change_neighbors_marker_path();
    let marker = change_neighbors::read_and_remove(&marker_path)?;

    // Per-session dedup: suppress an (edited file → neighbor) pair already
    // surfaced this session so re-editing the same file doesn't repeat the same
    // related code. The ledger is reset on SessionStart. Fail-open: an unreadable
    // ledger reads as empty, so nothing is wrongly suppressed.
    let seen_path = store.change_neighbors_seen_path();
    let seen = change_neighbors::read_seen(&seen_path);

    let mut fresh_keys: Vec<String> = Vec::new();
    let hits: Vec<String> = marker
        .neighbors
        .iter()
        .filter(|n| n.file_path != marker.edited_path)
        .filter(|n| neighbor_file_exists(project_root, &n.file_path))
        .filter(|n| {
            let key =
                change_neighbors::seen_key(&marker.edited_path, &n.file_path, n.name.as_deref());
            if seen.contains(&key) {
                return false;
            }
            fresh_keys.push(key);
            true
        })
        .map(|n| {
            prompts::hooks::edit_neighbor_line(
                &n.file_path,
                n.line_start,
                n.line_end,
                n.name.as_deref(),
                n.score,
            )
        })
        .collect();

    if hits.is_empty() {
        return None;
    }

    // Record only the pairs actually surfaced.
    change_neighbors::append_seen(&seen_path, &fresh_keys);

    let context = prompts::hooks::edit_related_context(&marker.edited_path, &hits);

    Some(json!({
        "hookSpecificOutput": {
            "hookEventName": event_name,
            "additionalContext": context,
        }
    }))
}

/// Merge several hook responses into one `additionalContext`.
///
/// Sources are joined in the order given, so callers pass the most urgent
/// first (index-ready before neighbor surfacing). Absent sources are skipped;
/// all-absent → `None`; a single present source is returned unchanged.
pub(super) fn combine_hook_responses(
    event_name: &str,
    sources: impl IntoIterator<Item = Option<Value>>,
) -> Option<Value> {
    let present: Vec<Value> = sources.into_iter().flatten().collect();
    match present.as_slice() {
        [] => None,
        [single] => Some(single.clone()),
        many => {
            let combined = many
                .iter()
                .map(|value| {
                    value["hookSpecificOutput"]["additionalContext"]
                        .as_str()
                        .unwrap_or("")
                })
                .collect::<Vec<_>>()
                .join("\n");
            Some(json!({
                "hookSpecificOutput": {
                    "hookEventName": event_name,
                    "additionalContext": combined,
                }
            }))
        }
    }
}

pub(super) fn watcher_alive(project_root: &Path, config: &Config) -> bool {
    let Ok(store) = Store::new(project_root, config) else {
        return false;
    };
    crate::store::marker::is_alive(
        &store.watch_marker_path(),
        Duration::from_secs(WATCH_MARKER_STALE_SECS),
    )
}

/// Decide whether a Write/Edit target deserves a background reindex spawn.
///
/// Mirrors the watcher's `WatchFilter::is_watchable` check so PostToolUse
/// doesn't fire a detached `claudix reindex-file` for `.claudix/manifest.json`,
/// `.git/HEAD`, gitignored build artifacts, or paths outside the project root.
/// Fail-open: any error during the check returns `true` so a legitimate edit
/// is still reindexed if the filter setup itself fails.
fn reindex_target_is_watchable(project_root: &Path, file_path: &str) -> bool {
    let raw = Path::new(file_path);
    let relative = if raw.is_absolute() {
        // Canonicalise both sides so a project root on a symlinked prefix
        // (macOS `/tmp` → `/private/tmp`) still strip-prefix-matches the
        // canonical raw path Claude Code hands us.
        let raw_canonical = raw.canonicalize();
        let raw_absolute = raw_canonical.as_deref().unwrap_or(raw);
        let root_canonical = project_root.canonicalize();
        let root_absolute = root_canonical.as_deref().unwrap_or(project_root);
        match raw_absolute.strip_prefix(root_absolute) {
            Ok(relative) => relative.to_path_buf(),
            Err(_) => return false,
        }
    } else {
        raw.to_path_buf()
    };
    if relative.as_os_str().is_empty() {
        return false;
    }
    match WatchFilter::load(project_root) {
        Ok(filter) => filter.is_watchable(&relative),
        Err(_) => true,
    }
}

/// Collect the distinct file paths that a tool input targets for reindexing.
///
/// Merges `file_path`, `notebook_path`, and the `files_modified` list (for
/// MultiEdit-style payloads). Duplicates are dropped; order is preserved.
///
/// Dedup keys on a canonical project-relative spelling (separators normalized,
/// absolute paths stripped to the project root), so the same file arriving as
/// both an absolute and a project-relative path spawns exactly one reindex
/// instead of racing two `drop_table`→`add` writers on the chunks table. The
/// original spelling is preserved in the output — the canonical form is only the
/// dedup key — so the downstream watchable check still sees what Claude sent.
fn reindex_paths_from_input(project_root: &Path, input: &ToolInput) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    let mut paths = Vec::new();

    let singles = input
        .file_path
        .as_deref()
        .into_iter()
        .chain(input.notebook_path.as_deref());

    let multi = input
        .files_modified
        .as_deref()
        .unwrap_or(&[])
        .iter()
        .map(String::as_str);

    for p in singles.chain(multi) {
        if seen.insert(canonical_dedup_key(project_root, p)) {
            paths.push(p.to_owned());
        }
    }
    paths
}

/// Canonical project-relative dedup key for a tool-input path. Strips an
/// absolute path to the project root (canonicalizing both sides so a symlinked
/// prefix still matches) and normalizes separators via [`RelativePath`]. A path
/// outside the project (or one that fails to strip) keys on its own normalized
/// spelling — it is never reindexed anyway, so a unique key is harmless.
fn canonical_dedup_key(project_root: &Path, file_path: &str) -> String {
    let raw = Path::new(file_path);
    let relative = if raw.is_absolute() {
        let raw_canonical = raw.canonicalize();
        let raw_absolute = raw_canonical.as_deref().unwrap_or(raw);
        let root_canonical = project_root.canonicalize();
        let root_absolute = root_canonical.as_deref().unwrap_or(project_root);
        raw_absolute
            .strip_prefix(root_absolute)
            .map(Path::to_path_buf)
            .unwrap_or_else(|_| raw.to_path_buf())
    } else {
        raw.to_path_buf()
    };
    RelativePath::from_path(&relative).as_str().to_owned()
}

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

    use std::fs;

    use serde_json::json;

    use crate::config::Config;
    use crate::hooks::{HookEvent, run};
    use crate::store::{Manifest, Store};

    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()
        );
    }

    // ── reindex_paths_from_input ──────────────────────────────────────────────

    fn make_tool_input(file_path: Option<&str>, files_modified: Option<Vec<&str>>) -> ToolInput {
        let json = serde_json::json!({
            "file_path": file_path,
            "files_modified": files_modified.map(|v| v.into_iter().collect::<Vec<_>>()),
        });
        serde_json::from_value(json).expect("must parse")
    }

    #[test]
    fn reindex_paths_only_file_path() {
        let input = make_tool_input(Some("src/lib.rs"), None);
        assert_eq!(
            reindex_paths_from_input(Path::new("/proj"), &input),
            vec!["src/lib.rs"]
        );
    }

    #[test]
    fn reindex_paths_only_files_modified() {
        let input = make_tool_input(None, Some(vec!["src/lib.rs", "src/main.rs"]));
        assert_eq!(
            reindex_paths_from_input(Path::new("/proj"), &input),
            vec!["src/lib.rs", "src/main.rs"]
        );
    }

    #[test]
    fn reindex_paths_both_deduped() {
        // file_path appears in files_modified too — must appear exactly once.
        let input = make_tool_input(Some("src/lib.rs"), Some(vec!["src/lib.rs", "src/main.rs"]));
        let paths = reindex_paths_from_input(Path::new("/proj"), &input);
        assert_eq!(paths, vec!["src/lib.rs", "src/main.rs"]);
    }

    #[test]
    fn reindex_paths_neither_field_is_empty() {
        let input = make_tool_input(None, None);
        assert!(reindex_paths_from_input(Path::new("/proj"), &input).is_empty());
    }

    #[test]
    fn reindex_paths_abs_and_relative_spelling_dedup_to_one() {
        // The same file arriving as an absolute path in file_path and a
        // project-relative path in files_modified must spawn exactly once.
        let fixture = TestFixture::new("small_rust").unwrap_or_else(|_| unreachable!());
        let abs = fixture.root().join("src/math.rs");
        let abs = abs.to_string_lossy().into_owned();
        let input = make_tool_input(Some(&abs), Some(vec!["src/math.rs"]));
        let paths = reindex_paths_from_input(fixture.root(), &input);
        assert_eq!(
            paths.len(),
            1,
            "abs + project-relative spelling of one file must dedup, got: {paths:?}"
        );
    }

    #[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());
    }

    #[test]
    fn reindex_target_is_watchable_rejects_index_internal_paths() {
        let fixture = TestFixture::new("small_rust").unwrap_or_else(|_| unreachable!());
        assert!(reindex_target_is_watchable(fixture.root(), "src/math.rs"));
        assert!(!reindex_target_is_watchable(
            fixture.root(),
            ".claudix/manifest.json"
        ));
        assert!(!reindex_target_is_watchable(fixture.root(), ".git/HEAD"));
        // Outside the project root: claude code generally resolves to absolute
        // paths inside CLAUDE_PROJECT_DIR, but defend in depth.
        let absolute_outside = std::env::temp_dir().join("nope.rs");
        assert!(!reindex_target_is_watchable(
            fixture.root(),
            &absolute_outside.to_string_lossy(),
        ));
    }

    #[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 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 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.watch_marker_path();
        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(())
    }

    // ── change-neighbors surfacing ──────────────────────────────────────────

    fn write_neighbors_marker(
        store: &Store,
        edited_path: &str,
        neighbors: Vec<crate::store::marker::change_neighbors::NeighborEntry>,
    ) {
        use crate::store::marker::change_neighbors::{ChangeNeighborsMarker, write};
        let marker = ChangeNeighborsMarker {
            edited_path: edited_path.to_owned(),
            neighbors,
        };
        write(&store.change_neighbors_marker_path(), &marker);
    }

    fn make_neighbor_entry(
        file_path: &str,
        name: &str,
        score: f32,
    ) -> crate::store::marker::change_neighbors::NeighborEntry {
        crate::store::marker::change_neighbors::NeighborEntry {
            file_path: file_path.to_owned(),
            line_start: 10,
            line_end: 25,
            name: Some(name.to_owned()),
            score,
        }
    }

    #[tokio::test]
    async fn neighbors_marker_surfaces_related_file_in_additional_context() -> 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()?;

        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.82)],
        );

        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        let response = response.unwrap_or(serde_json::Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();

        assert!(
            context.contains("src/math.rs"),
            "neighbor file must appear in additionalContext, got: {context}"
        );
        assert!(
            !context.contains("src/lib.rs:") || context.contains("edit of `src/lib.rs`"),
            "edited file must not appear as a hit in context, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn neighbors_marker_acked_on_read() -> 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()?;

        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.80)],
        );

        assert!(
            store.change_neighbors_marker_path().exists(),
            "marker must exist before read"
        );

        let _ = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");

        assert!(
            !store.change_neighbors_marker_path().exists(),
            "marker must be removed after being read (ack)"
        );
        Ok(())
    }

    #[tokio::test]
    async fn no_neighbors_marker_produces_no_context() -> 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()?;

        // No marker written — must produce None.
        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        assert!(
            response.is_none(),
            "absent marker must produce no additionalContext"
        );
        Ok(())
    }

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

        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.82)],
        );

        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        assert!(
            response.is_none(),
            "surface_related_on_edit = false must suppress output even when marker is present"
        );
        Ok(())
    }

    #[tokio::test]
    async fn edited_file_never_surfaced_as_own_neighbor() -> 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()?;

        // Simulate a marker where the only neighbor IS the edited file (must not happen in
        // practice but the hook layer must not surface it either way).
        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![
                make_neighbor_entry("src/lib.rs", "greet", 0.99), // same as edited
                make_neighbor_entry("src/math.rs", "add", 0.80),
            ],
        );

        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        let response = response.unwrap_or(serde_json::Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();

        assert!(
            context.contains("src/math.rs"),
            "non-edited neighbor must be in context, got: {context}"
        );
        // The hook layer must filter out the edited file even if the marker
        // somehow carries it (defense in depth on top of neighbors() exclusion).
        assert!(
            !context.contains("src/lib.rs:"),
            "edited file must not appear as a hit in context, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn repeated_identical_neighbor_pair_is_suppressed() -> 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()?;

        // First take surfaces the (src/lib.rs → src/math.rs) pair.
        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.82)],
        );
        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        let response = response.unwrap_or(serde_json::Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("src/math.rs"),
            "first take must surface the neighbor, got: {context}"
        );

        // read_and_remove deletes the marker on each take, so re-write the SAME
        // marker before the second take.
        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.82)],
        );
        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        assert!(
            response.is_none(),
            "identical (edited → neighbor) pair already surfaced this session must be suppressed"
        );
        Ok(())
    }

    #[tokio::test]
    async fn same_neighbor_via_different_edited_file_still_surfaces() -> 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()?;

        // First: edited=src/lib.rs → src/math.rs, surfaces and records the key.
        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.82)],
        );
        let _ = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");

        // Same neighbor, different edited file → different dedup key → surfaces.
        write_neighbors_marker(
            &store,
            "src/other.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.82)],
        );
        let response = take_change_neighbors_context(fixture.root(), Some(&config), "PostToolUse");
        let response = response.unwrap_or(serde_json::Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();
        assert!(
            context.contains("src/math.rs"),
            "same neighbor via a different edited file must still surface, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn session_start_clears_seen_ledger() -> 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()?;

        // Seed a dummy key into the per-session dedup ledger.
        let seen_path = store.change_neighbors_seen_path();
        fs::write(&seen_path, "src/lib.rs\tsrc/math.rs\tadd\n")?;
        assert!(seen_path.exists(), "ledger must exist before SessionStart");

        run(fixture.root(), HookEvent::SessionStart, "{}").await?;

        assert!(
            !seen_path.exists(),
            "SessionStart must reset the dedup ledger"
        );
        Ok(())
    }

    #[tokio::test]
    async fn combine_both_messages_when_both_present() -> 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()?;

        // Set up index-ready marker.
        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 = 1;
        manifest.chunk_count = 2;
        manifest.last_full_index_at = Some(crate::util::now_rfc3339());
        store.write_manifest(&manifest)?;

        // Set up neighbors marker.
        write_neighbors_marker(
            &store,
            "src/lib.rs",
            vec![make_neighbor_entry("src/math.rs", "add", 0.80)],
        );

        let response = run(fixture.root(), HookEvent::PostToolUse, "{}").await?;
        let response = response.unwrap_or(serde_json::Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();

        assert!(
            context.contains("indexing complete"),
            "combined context must include index-ready message, got: {context}"
        );
        assert!(
            context.contains("src/math.rs"),
            "combined context must include neighbor file, got: {context}"
        );
        Ok(())
    }

    // ── read-time surfacing ─────────────────────────────────────────────────

    /// Seed the store directly with chunks at explicit line ranges and vectors,
    /// bypassing embedding so cosine similarities are fully controlled.
    async fn seed_rows(store: &Store, config: &Config, rows: &[(&str, &str, u32, u32, Vec<f32>)]) {
        use crate::types::{
            ByteRange, Chunk, ChunkId, ChunkKind, EmbeddedChunk, FileHash, Language, LineRange,
            RelativePath,
        };
        // Materialize each referenced file on disk so the neighbor-existence
        // guard (which drops surfaced neighbors whose file was deleted) treats
        // them as live — these tests assert real files get surfaced.
        for (path, ..) in rows {
            let abs = store.project_root().join(path);
            if let Some(parent) = abs.parent() {
                let _ = std::fs::create_dir_all(parent);
            }
            let _ = std::fs::write(&abs, "// seeded\n");
        }
        let embedded: Vec<EmbeddedChunk> = rows
            .iter()
            .enumerate()
            .map(|(i, (path, name, start, end, vector))| {
                let chunk = Chunk {
                    id: ChunkId(i as u64 + 1),
                    file_path: RelativePath::new(*path),
                    language: Language::Rust,
                    kind: ChunkKind::Function,
                    name: Some((*name).to_owned()),
                    line_range: LineRange {
                        start: *start,
                        end: *end,
                    },
                    byte_range: ByteRange { start: 0, end: 50 },
                    file_hash: FileHash([0u8; 16]),
                    content: format!("pub fn {name}() {{}}"),
                };
                EmbeddedChunk {
                    chunk,
                    vector: vector.clone(),
                }
            })
            .collect();
        assert!(store.replace_chunks(&embedded, config).await.is_ok());
    }

    fn read_config_on() -> Config {
        let mut config = stub_config();
        config.hooks.surface_related_on_read = true;
        config.hooks.related_top_k = 5;
        config.hooks.related_min_similarity = 0.5;
        config
    }

    #[test]
    fn chunk_overlaps_window_respects_bounds() {
        // Bounded window [10, 20].
        assert!(
            chunk_overlaps_window(8, 12, 10, Some(20)),
            "straddles start"
        );
        assert!(chunk_overlaps_window(15, 18, 10, Some(20)), "inside window");
        assert!(chunk_overlaps_window(18, 25, 10, Some(20)), "straddles end");
        assert!(!chunk_overlaps_window(1, 9, 10, Some(20)), "ends before");
        assert!(!chunk_overlaps_window(21, 30, 10, Some(20)), "starts after");
        // Open-ended window [10, EOF]: only the lower bound constrains.
        assert!(chunk_overlaps_window(50, 60, 10, None), "far below EOF");
        assert!(!chunk_overlaps_window(1, 9, 10, None), "ends before start");
        assert!(
            chunk_overlaps_window(u32::MAX, u32::MAX, u32::MAX, Some(u32::MAX)),
            "saturating read windows still match the last line"
        );
    }

    #[test]
    fn read_surfacing_defaults_off() {
        assert!(!Config::default().hooks.surface_related_on_read);
    }

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

        // The read file's chunk at lines 10-20 shares a near-duplicate vector
        // with a chunk in another file; an unrelated chunk sits orthogonal.
        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "twin",
                    40,
                    58,
                    vec![0.99, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/other.rs",
                    "unrelated",
                    1,
                    5,
                    vec![0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;

        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": "src/foo.rs", "offset": 12, "limit": 6 }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        let response = response.unwrap_or(Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();

        assert!(
            context.contains("src/bar.rs"),
            "neighbor file must be surfaced, got: {context}"
        );
        assert!(
            context.contains("lines 12-17"),
            "context must name the read region, got: {context}"
        );
        assert!(
            !context.contains("src/foo.rs:"),
            "read file must not be listed as its own neighbor, got: {context}"
        );
        Ok(())
    }

    #[tokio::test]
    async fn ranged_read_absolute_path_surfaces_neighbor() -> Result<()> {
        // Claude Code sends absolute paths in tool_input.file_path; verify they
        // are resolved to relative before matching against the store.
        let fixture = TestFixture::new("small_rust")?;
        let config = read_config_on();
        write_config(fixture.root(), &config);
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;

        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "twin",
                    40,
                    58,
                    vec![0.99, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;

        // Use the absolute path as Claude Code would supply it.
        let abs_path = fixture.root().join("src/foo.rs");
        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": abs_path, "offset": 12, "limit": 6 }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        let response = response.unwrap_or(Value::Null);
        let context = response["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .unwrap_or_default();

        assert!(
            context.contains("src/bar.rs"),
            "absolute-path read must still surface the neighbor, got: {context}"
        );
        Ok(())
    }

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

        // seed_rows materializes both files on disk; the neighbor (bar.rs) is
        // then deleted out-of-band so only its now-stale chunk remains indexed.
        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "twin",
                    40,
                    58,
                    vec![0.99, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;
        assert!(fs::remove_file(store.project_root().join("src/bar.rs")).is_ok());

        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": "src/foo.rs", "offset": 12, "limit": 6 }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        assert!(
            response.is_none(),
            "a neighbor whose file was deleted on disk must not be surfaced"
        );
        Ok(())
    }

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

        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "twin",
                    40,
                    58,
                    vec![0.99, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;

        // No offset or limit → whole-file read → noop.
        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": "src/foo.rs" }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        assert!(
            response.is_none(),
            "full-file read must not surface neighbors"
        );
        Ok(())
    }

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

        // The read chunk's neighbor sits below the 0.5 floor (orthogonal vector).
        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "stranger",
                    40,
                    58,
                    vec![0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;

        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": "src/foo.rs", "offset": 12, "limit": 6 }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        assert!(response.is_none(), "no neighbor clears the floor → noop");
        Ok(())
    }

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

        // Read file's only chunk spans 10-20; a near-duplicate exists elsewhere.
        // The read window 1-5 misses the chunk entirely → no query vectors → noop,
        // even though a strong neighbor exists.
        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "twin",
                    40,
                    58,
                    vec![0.99, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;

        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": "src/foo.rs", "offset": 1, "limit": 5 }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        assert!(
            response.is_none(),
            "window missing the chunk span must surface nothing"
        );
        Ok(())
    }

    #[tokio::test]
    async fn read_surfacing_disabled_skips_store() -> Result<()> {
        let fixture = TestFixture::new("small_rust")?;
        let mut config = stub_config();
        config.hooks.surface_related_on_read = false;
        write_config(fixture.root(), &config);
        let store = Store::new(fixture.root(), &config)?;
        store.ensure_layout()?;
        seed_rows(
            &store,
            &config,
            &[
                (
                    "src/foo.rs",
                    "target",
                    10,
                    20,
                    vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
                (
                    "src/bar.rs",
                    "twin",
                    40,
                    58,
                    vec![0.99, 0.01, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                ),
            ],
        )
        .await;

        let payload = json!({
            "tool_name": "Read",
            "tool_input": { "file_path": "src/foo.rs", "offset": 12, "limit": 6 }
        });
        let response = run(fixture.root(), HookEvent::PostToolUse, &payload.to_string()).await?;
        assert!(
            response.is_none(),
            "flag off must surface nothing on a ranged read"
        );
        // The reindex invariant must hold regardless of the read flag: a Read
        // never triggers a background reindex — no change-neighbors marker
        // appears (that is only written by the reindex path).
        assert!(
            !store.change_neighbors_marker_path().exists(),
            "Read must never trigger a reindex"
        );
        Ok(())
    }
}