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
//! `CodeIndexer`: hybrid HNSW + BM25 + RRF search pipeline.
//!
//! Why: this is the central orchestrator that ties embeddings, vector search,
//! lexical search, and intent-based weight routing into a single `search()` call.
//! What: holds an `Embedder`, a `VectorStore`, and an in-memory chunk corpus;
//! `search()` runs both lanes in parallel, fuses with RRF, and returns the
//! top-k chunks with their fused score and per-result `match_reason`.
//! Test: see the `tests` submodule — RRF unit coverage lives in `search::rrf`,
//! and the integration test `test_search_integration` indexes 3 chunks and
//! verifies the most-relevant one ranks first.
//!
//! Module layout (issue #96 — god-object split):
//! * `mod.rs` (this file): types, free helpers, struct definition, constructors.
//! * `ingest`: add/index/batch parse+embed/commit pipeline.
//! * `persist`: snapshot/restore + background incremental persist.
//! * `files`: remove + lookup + entity-exact-match helpers.
//! * `search`: hybrid query pipeline (HNSW + BM25 + RRF + KG + MMR).
//! * `tests`: every test in one place so private fields stay accessible.
use ;
use ;
use NonZeroUsize;
use ;
use ;
use Instant;
use LruCache;
use ;
use RwLock;
use crateBm25Index;
use crate;
use crateEmbedder;
use crateRawEntity;
use crateVectorStore;
use crateSymbolGraph;
pub
pub
pub
pub use KG_REFINE_THRESHOLD;
/// LRU capacity (entries) for the per-indexer query embedding cache.
const QUERY_CACHE_CAPACITY: usize = 256;
/// Oversample factor for the HNSW lane before RRF fusion.
pub const HNSW_OVERSAMPLE: usize = 4;
/// Default LRU capacity for the per-indexer chunk embedding cache.
///
/// Each entry is `dim × 4` bytes (384-dim f32 ≈ 1 536 B). 1 000 entries ≈
/// ~1.5 MB of RAM per index. Evicted entries are simply re-embedded on demand
/// (MMR rerank gracefully falls back when an embedding is missing). Lowered
/// from 10 000 → 1 000 (issue #79) after a daemon was observed at 43.9 GB RSS;
/// the cache was a meaningful contributor on multi-index hosts. Override
/// at runtime via `TRUSTY_EMBEDDING_CACHE`.
const DEFAULT_EMBEDDING_CACHE_CAP: usize = 1_000;
/// Read the embedding-cache LRU cap from the environment, with a sane default.
/// Default idle window (seconds) after which a durably-backed index's
/// in-memory `chunks` HashMap is evicted to reclaim heap.
///
/// Why (idle-memory audit, follow-up to the redb-cache + embedding-LRU quick
/// wins): the earlier wins capped the redb page cache and the chunk-embedding
/// LRU, but the raw `chunks: Arc<RwLock<HashMap<String, RawChunk>>>` still held
/// every chunk's *text* resident for the index's entire lifetime — on a 200k
/// chunk corpus that is hundreds of MB of `String` heap per index that the
/// query hot path no longer even reads (since issue #28 it materialises top-k
/// results straight from the mmap-backed redb corpus via
/// `CorpusStore::get_chunks`). An idle index therefore parks that whole map in
/// RAM for nothing. Evicting it after a quiet period reclaims the heap; the few
/// remaining in-memory readers (`grep_fallback_search`, `all_chunks`,
/// `enumerate_chunks`, the `fetch_chunks_for_ids` fallback) lazily rehydrate
/// from redb on the next access. 300 s (5 min) is long enough that an actively
/// queried index is never evicted mid-session, short enough that a daemon left
/// idle overnight shrinks back to its durable baseline.
/// What: 300 seconds, used by [`crate::core::indexer::idle_evict_secs`] when
/// `TRUSTY_CHUNKS_IDLE_EVICT_SECS` is unset.
/// Test: `idle_evict_secs_default_and_env_override`.
const DEFAULT_CHUNKS_IDLE_EVICT_SECS: u64 = 300;
/// Resolve the in-memory-chunks idle-eviction window (in seconds) from the
/// environment, falling back to [`DEFAULT_CHUNKS_IDLE_EVICT_SECS`].
///
/// Why: operators on memory-constrained hosts may want a tighter window
/// (evict sooner) while large-corpus hosts that re-query frequently may want
/// to disable eviction entirely. Making it env-tunable mirrors the
/// `TRUSTY_REDB_CACHE_MB` / `TRUSTY_EMBEDDING_CACHE` precedent without a
/// recompile.
/// What: reads `TRUSTY_CHUNKS_IDLE_EVICT_SECS` as `u64` seconds. A value of `0`
/// **disables** idle eviction (the in-memory map is never dropped). An
/// unset / empty / unparseable value falls back to the default (a warn is
/// logged on a non-empty unparseable value so typos surface).
/// Test: `idle_evict_secs_default_and_env_override`.
pub
/// Default hard cap on chunks per index. Also used as the HNSW
/// `max_elements`-style sanity guard. 200 000 chunks × ~5 KB metadata ≈ 1.0 GB
/// of RAM-resident chunk corpus on a single index. Lowered from 500 000 →
/// 200 000 (issue #79) — the previous default permitted >2.5 GB / index just
/// for chunk metadata, on top of HNSW and BM25 structures. Operators with
/// large monorepos can still raise this via `TRUSTY_MAX_CHUNKS`.
const DEFAULT_MAX_CHUNKS_PER_INDEX: usize = 200_000;
/// Read the per-index chunk cap from the environment, with a sane default.
pub
/// Batch size for the fastembed ONNX call when bulk-indexing files.
///
/// 128 chunks per batch balances SIMD/tensor-setup amortisation against ONNX
/// session arena growth. ORT retains per-session activation buffers sized to
/// the largest batch it has seen; on large repos a 256-chunk batch combined
/// with a 512-file reindex batch caused the arena to grow into the tens of
/// GBs and trigger macOS Jetsam kills. 128 keeps the per-call tensor footprint
/// bounded while still being large enough to amortise ONNX kernel launch
/// overhead.
///
/// Override at runtime via `TRUSTY_MAX_BATCH_SIZE` (clamped to
/// `[EMBED_BATCH_MIN, EMBED_BATCH_MAX]`).
///
/// Default safety-net batch size when `TRUSTY_MAX_BATCH_SIZE` is unset.
///
/// Raised from 32 → 64 (issue #19): the ORT arena allocator is disabled on
/// the CPU path (`with_arena_allocator(false)` in trusty-common's embedder),
/// so transient allocation is freed per call and 64 is the minimum safe
/// value that amortises ONNX kernel launch overhead. The authoritative
/// per-tier default is still computed by [`crate::core::MemoryPolicy`] and
/// written back into `TRUSTY_MAX_BATCH_SIZE` before this function is called;
/// this constant only kicks in when the env is unset.
const DEFAULT_EMBED_BATCH_SIZE: usize = 64;
/// Floor for env-clamped batch size. Aligned with
/// `core::memory_policy::MIN_COMPUTED_BATCH_SIZE` (32). Raised from 8 → 32
/// (issue #19): with the CPU arena disabled the prior 200 MB/slot estimate
/// no longer applies, so 32 is the new minimum safe value.
const EMBED_BATCH_MIN: usize = 32;
/// Ceiling for env-clamped batch size. Aligned with
/// `core::memory_policy::MAX_COMPUTED_BATCH_SIZE` (512). The GPU opt-out path
/// (`TRUSTY_MAX_BATCH_SIZE_EXPLICIT=1` on CUDA/CoreML) reaches this ceiling
/// in production.
const EMBED_BATCH_MAX: usize = 512;
/// Read the embedding batch size from `TRUSTY_MAX_BATCH_SIZE`, clamped to
/// `[EMBED_BATCH_MIN, EMBED_BATCH_MAX]`. Falls back to `DEFAULT_EMBED_BATCH_SIZE`
/// when unset or unparseable.
///
/// Why: large repos can exhaust process memory if batches grow unbounded. This
/// gives operators a runtime knob to dial batch size up (faster indexing on
/// memory-rich hosts) or down (safer on constrained hosts) without rebuilding.
/// What: parses env, clamps via `.clamp()`. Filter-then-clamp ensures both
/// missing and zero values fall through to the default.
/// Test: see `tests::test_embed_batch_size_env_clamp`.
pub
/// Legacy default score multiplier applied to chunks brought in via KG
/// expansion. Retained for backwards-compat documentation: the live pipeline
/// now uses [`EdgeKind::score_multiplier`] (issue #18) so each edge type
/// contributes its own weight. Tests still reference this constant when
/// validating the `CallsFunction` baseline.
pub const KG_EXPAND_SCORE_FACTOR: f32 = 0.7;
/// Default BFS depth for KG expansion (1 hop = direct callers/callees only).
pub const KG_EXPAND_HOPS: usize = 1;
/// How many committed batches must elapse between background HNSW snapshots
/// (issue #29).
///
/// Why: `spawn_incremental_persist` used to fire after *every* committed
/// batch. The chunk corpus is already persisted transactionally per batch by
/// `commit_corpus_to_redb`, so the per-batch work that actually mattered for
/// crash-safety was the redb write — the HNSW `Index::save` is a pure backup
/// that takes hundreds of ms on a large graph. On a 14k-file reindex (128
/// files/batch → ~110 batches) that was ~110 full graph saves; throttling to
/// one every 16 batches cuts that to ~7 (plus one forced save at reindex
/// completion), reclaiming ~15+ seconds of redundant I/O without weakening
/// durability — a crash loses at most the last 16 batches' HNSW vectors,
/// which the next reindex re-embeds anyway, and the redb corpus is intact.
/// What: the batch-count modulus used by `spawn_incremental_persist`.
/// Test: `tests::test_incremental_persist_throttles_to_interval`.
pub const HNSW_SNAPSHOT_BATCH_INTERVAL: u32 = 16;
/// A search result returned to callers.
/// File-type filter mode for the unified search tool (issue #77, final
/// design).
///
/// Why: the same hybrid index serves four distinct callers — code search
/// (source files only), text/doc search (prose docs only), data search
/// (JSON/YAML/CSV/TOML/etc. only), and an unrestricted mode that returns
/// whatever the index produced. The previous multiplicative-penalty
/// design still let prose/config outrank source in code mode whenever the
/// raw BM25 score was high enough — CHANGELOG.md routinely came back at
/// rank 1. The revised design replaces the penalty matrix with a **hard
/// file-type filter** applied once per result after RRF / MMR /
/// materialization: chunks whose file is not in the allowed set for the
/// requested mode are dropped entirely. No score distortion, no
/// cross-contamination.
/// What: `Code` (default) returns only chunks from source-code extensions
/// (.rs, .ts, .py, .go, …). `Text` returns only prose / documentation
/// extensions (.md, .rst, .txt, …) plus path-based named docs (README*,
/// CHANGELOG*, LICENSE*, NOTICE*, CONTRIBUTING*) regardless of
/// extension. `Data` returns only structured-data / config / schema files
/// (.json, .yaml, .toml, .xml, .csv, .sql, lockfiles, …). `All` disables
/// the filter and returns every chunk the index produced. Archive
/// downranking (issue #75 — path keywords, `#[deprecated]`, marker files,
/// stale git mtime) still applies within each mode. Exposed to MCP /
/// HTTP callers as the lowercase strings `"code"`, `"text"`, `"data"`,
/// `"all"`.
/// Test: covered by `docs_penalty::tests` (per-mode allow/reject) and
/// the per-mode integration tests in `indexer::tests`.
/// Query parameters for hybrid search.
/// Stage selector for a single search query (issue #109, Phase 1; extended
/// in issue #138).
///
/// Why: lets callers (HTTP `?stage=...` or the per-lane MCP tools added in
/// #138) force a specific lane combination even when the index is fully
/// ready. Pushes intent classification to the LLM — the LLM picks
/// `search_lexical` / `search_semantic` / `search_kg` and the server simply
/// routes the lane mix.
///
/// What: a lowercase-serialised enum mapping each variant to a fixed lane
/// combination in [`CodeIndexer::search`]. `Lexical` runs BM25 plus the
/// grep-fallback only (no HNSW, no KG). `Semantic` runs BM25 plus HNSW
/// via RRF (no KG expansion, no community-cohesion bonus). `Graph` runs
/// the full BM25 plus HNSW plus KG expansion pipeline (hybrid AND).
/// `None` keeps the legacy adaptive behaviour where the daemon's
/// `search_capabilities` decides which lanes participate.
///
/// Test: `stage_1_completes_and_search_works_before_embedding` (lexical),
/// `search_semantic_stage_skips_kg_expansion` (semantic), and
/// `search_graph_stage_forces_kg_expansion_on_definition_query` (graph)
/// in `core::indexer::tests`. Tool-level routing is covered by
/// `mcp::tools::tests::search_*_tool_routes_to_*_stage`.
/// Stable u64 hash of a query string. Used as the LRU cache key so we don't
/// retain the full string twice (LRU stores the embedding payload only).
pub
/// Build a 7-line snippet centered on the chunk content for token-efficient output.
pub
/// Resolve a stored chunk `file` string to an absolute path string.
///
/// Why (issue #402 — relocation resilience): as of the relative-path storage
/// change, newly indexed chunks store `file` as a path relative to
/// `root_path` (e.g. `"src/lib.rs"` instead of `"/Users/me/proj/src/lib.rs"`).
/// Older indexes still carry absolute paths. This helper normalises both
/// representations to an absolute path so all read-side callers — search
/// results, `list_chunks`, `get_call_chain`, MCP outputs — always return
/// absolute paths to callers, regardless of when the index was created.
///
/// What: if `raw_file` starts with the OS path separator (i.e. is already
/// absolute) it is returned as-is. Otherwise `root_path` is joined with
/// `raw_file` to produce an absolute path string.
///
/// Test: `tests::resolve_chunk_file_relative_becomes_absolute` and
/// `tests::resolve_chunk_file_absolute_passthrough` in `indexer::tests`.
pub
/// Materialize a `RawChunk` into a `CodeChunk` with the given score, match
/// reason, and optional compact snippet.
///
/// Why: four call sites (`similar_by_embedding`, `all_chunks`,
/// `enumerate_chunks`, the `search` materialization tail) used to inline the
/// same 18-field struct literal. Consolidating them removes ~60 lines of
/// duplication and the inevitable per-site drift when new fields are added.
/// What: clones every metadata field and derives `chunk_depth` (clamped to u8).
/// The `root_path` argument is used to resolve a relative `raw.file` to an
/// absolute path via [`resolve_chunk_file`] (issue #402).
/// Test: covered indirectly by every search/materialization test in this file.
pub
/// Populate `virtual_terms` on each chunk from entities whose source line
/// falls within the chunk's `[start_line, end_line]` range.
///
/// Why: two call sites (`index_file` and `parse_and_embed_files`) used the
/// same dedupe-by-entity-text loop. Extracting prevents drift.
/// What: for each chunk, walks `entities` once, inserting each entity's text
/// at most once into a fresh `virtual_terms` vector.
/// Test: covered by `test_virtual_terms_populated_from_entities`.
pub
/// Score multiplier applied to a chunk for Definition-intent queries (issue #92).
///
/// Why: Definition queries (e.g. "struct CodeChunk fields") should surface the
/// canonical source-file declaration, not the Markdown / TOML / YAML file that
/// happens to mention the symbol many times. We demote doc/config files by 50%
/// only for Definition intent; Conceptual queries still surface `.md` docs.
/// What: returns `0.5` when the path ends with a known doc/config extension,
/// `1.0` otherwise.
/// Test: covered by `test_file_type_multiplier_demotes_docs` and the
/// integration test `test_definition_demotes_markdown_below_source`.
pub
/// Structural-definition score boost applied to a chunk when Definition-intent
/// queries hit a struct/enum/class/trait declaration whose `function_name`
/// contains a query token as a substring (case-insensitive) (issue #117).
///
/// Why: queries containing struct-name acronyms (`HNSW`, `BM25`, `RRF`, `ORT`)
/// or PascalCase identifiers were under-fired by the v0.8.2 ranker. The
/// classifier upgrade (#119) routes them to `Definition`, which already
/// demotes docs and runs the grep lane; the additional structural boost here
/// closes the gap on the cross-file case where the canonical declaration
/// (e.g. `hnsw_store.rs::HnswStore`) was being out-ranked by usage chunks
/// elsewhere in the codebase (e.g. `retrieval.rs` calling into HNSW). A 2.0×
/// multiplier is large enough to lift the declaration from rank ~8 to top-3
/// on the v0.8.1 benchmark scenarios but small enough not to drown out the
/// branch-modified boost (`1.0..=3.0`) when both fire on the same chunk.
/// What: a flat `2.0` multiplier. Symbolic so the constant is easy to find
/// when re-tuning.
/// Test: `test_struct_definition_boost_surfaces_struct_over_usage` in
/// `indexer::tests`.
pub const STRUCT_DEFINITION_BOOST: f32 = 2.0;
/// Decide whether `chunk_type` participates in the Definition-intent
/// structural boost (issue #117).
///
/// Why: the boost is intentionally narrow — only chunks that ARE the
/// declaration of a type are eligible. Free code, methods, and docstrings
/// stay on the default multiplier so usage and method-of-struct chunks
/// don't accidentally outrank the struct definition itself.
/// What: returns `true` for `Struct`, `Enum`, `Class`, `Trait`, and
/// `TypeAlias`; `false` for everything else. Note: `Function` and `Method`
/// are handled by [`is_function_definition_chunk_type`] (issue #122).
/// Test: covered indirectly by
/// `test_struct_definition_boost_surfaces_struct_over_usage`.
pub
/// Decide whether `chunk_type` participates in the Definition-intent
/// function-definition boost (issue #122).
///
/// Why: the synthetic-corpus baseline (#123) reproduced a regression where
/// function-name queries (e.g. `BRUSILOV_EPOCH`, `get_call_chain`) returned
/// usage sites or string-literal occurrences at rank 1 instead of the
/// canonical function declaration. The existing struct-definition boost
/// (#117) deliberately excluded `Function`/`Method` because we assumed the
/// `inject_entity_exact_match` lane would carry them — but in practice
/// usage chunks with high BM25 TF can still out-rank the synthetic-injected
/// entity hit once RRF fuses lanes. Extending the boost to function-like
/// chunks closes that gap.
/// What: returns `true` for `Function` and `Method` (constructor variants
/// would also belong here but the current `ChunkType` enum has no
/// `Constructor` variant — tree-sitter constructors get classified as
/// `Function` or `Method` depending on the language); `false` for
/// everything else. Critically: `Constant` is excluded so chunks whose
/// only mention of the query token is a string literal (e.g.
/// `mcp_descriptor.rs` with `"get_call_chain"` in a JSON tool descriptor)
/// are NOT boosted.
/// Test: covered by
/// `test_function_definition_boost_surfaces_function_over_string_literal_usage`
/// and `test_method_definition_boost_fires`.
pub
/// Lowercase the meaningful query tokens for the Definition-intent structural
/// boost (issue #117).
///
/// Why: the boost only fires when a chunk's `function_name` literally matches
/// one of the query tokens. Tokenising the same way at boost-decision time
/// keeps the rule predictable and unit-testable.
/// What: splits on whitespace, drops tokens shorter than 2 characters, and
/// lowercases each remaining token. Whitespace-only or empty inputs return
/// an empty Vec.
/// Test: covered indirectly by
/// `test_struct_definition_boost_surfaces_struct_over_usage`.
pub
/// Map (`in_hnsw`, `in_bm25`, `in_kg`) booleans to a stable `match_reason`
/// label.
///
/// Why: lifted out of `search` to keep the materialization loop short and
/// to make the precedence rules unit-testable in isolation.
/// What: direct hits (HNSW and/or BM25) take precedence over KG-only paths.
/// Issue #75: the `(false,false,false)` arm is reserved for the grep
/// fallback lane and now returns the canonical `"fallback:ripgrep"` label.
/// Test: covered indirectly by `test_kg_expansion_marks_neighbours_with_hybrid_kg`
/// and `test_compute_match_reason_fallback_label`.
pub
/// On-disk shape of a chunk corpus snapshot (issue #85). Stored as JSON next
/// to the HNSW snapshot so the daemon can restore an index without re-parsing
/// the source tree.
///
/// Why: BM25 + the symbol graph are both derivable from the chunk corpus, so
/// persisting just the chunks (and the per-file entity lists) is enough to
/// warm-boot the whole search pipeline. We deliberately do NOT persist BM25
/// posting lists — rebuilding them from chunks at load time is O(N tokens)
/// and avoids a second on-disk schema to migrate.
/// What: versioned wrapper around `Vec<RawChunk>` plus the entities map.
/// Test: covered by `tests::test_save_chunks_roundtrip`.
pub
/// Output of the parse+embed phase: chunks paired with their (optional)
/// embeddings plus the per-file entity lists, ready to be committed into the
/// indexer's shared state. Held without any write lock so it can be shipped
/// between async tasks freely.
/// Per-batch timings emitted by [`CodeIndexer::commit_parsed_batch`]. Captures
/// the cost of the commit-phase work (BM25 ingest, vector upsert, KG rebuild).
///
/// Why: surfaced to the reindex orchestrator so it can accumulate per-subsystem
/// totals across all batches and emit them in the SSE `complete` event. This
/// gives operators visibility into where indexing time was actually spent and
/// is the smoking-gun signal for the "embedder silently fell back to BM25"
/// failure mode (`vector_count == 0` while `chunks > 0`).
/// `CodeIndexer`: hybrid search engine for one named index.
///
/// Fields are crate-visible so the submodule `impl` blocks (`ingest`, `persist`,
/// `files`, `search`) can mutate state without going through accessors. They
/// remain `pub(super)`-equivalent from outside `core::indexer`.
/// Coalescing state for `spawn_incremental_persist`.
///
/// Why: prior to this guard, every call to `commit_parsed_batch` spawned a
/// fire-and-forget tokio task that cloned the **entire** chunk corpus
/// (every `RawChunk.content` String) into a `Vec<RawChunk>` and serialized
/// it to JSON. On a 200k-chunk corpus that's ~400 MB of `Vec<RawChunk>`
/// plus another ~800 MB of serialized `Vec<u8>` per task. A reindex emits
/// one commit per 128 files, so a 76 800-file repo would stack ~600 of
/// these tasks. With no concurrency limit, RAM ballooned to 46–174 GB
/// before the OS killed the daemon (observed on ~/Duetto/cto and
/// ~/Duetto/repos/duetto). The `TRUSTY_MEMORY_LIMIT_MB` poller could not
/// catch it because the runaway allocator was a detached task ladder, not
/// the reindex loop itself.
///
/// What: `in_flight` guarantees only one persist task is alive at a time
/// for this index; `dirty` lets later commits coalesce — when the running
/// task completes it re-runs once if `dirty` was set during its snapshot,
/// guaranteeing the on-disk file converges to the latest in-memory state
/// without ever allocating more than ~1× the corpus footprint.
///
/// Test: `tests::test_persist_coalesces_concurrent_calls`.
pub