basemind 0.17.0

Full AI context layer over MCP — tree-sitter code-map, document RAG (PDF/Office/HTML/email + OCR + reranker), shared agent memory, on-demand web crawl, git history + blame + per-symbol diff. 300+ languages, 10+ coding-agent harnesses, content-addressed Fjall + LanceDB.
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
//! Byte-level key encoding/decoding for the Fjall inverted index.
//!
//! Each function encodes a primary key for one partition. Companion `parse_*` functions
//! decode the components back so the reader path can reconstruct `(rel_path, byte offset)`
//! from a raw key buffer.
//!
//! All length-prefixed components use `u16` big-endian — paths and identifiers in real code
//! are far below 64 KiB. Byte offsets in source files use `u32` big-endian. Big-endian
//! orderings keep prefix-scan semantics intuitive: a `range("foo\0".."foo\0\xff")` over
//! `calls_by_callee` returns exactly the hits for callee `"foo"`.

use crate::extract::SymbolKind;
use crate::path::RelPath;

/// `u16:name_len ‖ name`. Internal helper.
///
/// Returns `None` when `bytes` exceeds 65535 bytes (the u16 ceiling). Path encoders that
/// call this for `RelPath` components may ignore the return value with `let _ = …` — real
/// file paths never hit 64 KiB. Identifier encoders (`symbol_by_name`, `call_by_callee`,
/// `import_by_module`, `import_by_path`, `impl_by_trait`, `impl_by_path`) return `Option`
/// and propagate `None` to their callers so that pathologically long tokens are silently
/// skipped rather than panicking inside a rayon `par_iter`.
fn write_len_prefixed(out: &mut Vec<u8>, bytes: &[u8]) -> Option<()> {
    let len = u16::try_from(bytes.len()).ok()?;
    out.extend_from_slice(&len.to_be_bytes());
    out.extend_from_slice(bytes);
    Some(())
}

fn read_len_prefixed(buf: &[u8], cursor: &mut usize) -> Option<Vec<u8>> {
    if buf.len() < *cursor + 2 {
        return None;
    }
    let len = u16::from_be_bytes([buf[*cursor], buf[*cursor + 1]]) as usize;
    *cursor += 2;
    if buf.len() < *cursor + len {
        return None;
    }
    let out = buf[*cursor..*cursor + len].to_vec();
    *cursor += len;
    Some(out)
}

/// Zero-copy variant of `read_len_prefixed` — returns a borrowed slice into `buf` instead
/// of allocating a `Vec<u8>`. Use this on the parse path when the next consumer (e.g.
/// `RelPath::from(&[u8])`) copies the bytes internally; the intermediate `Vec` would be
/// a wasted allocation.
fn read_len_prefixed_ref<'buf>(buf: &'buf [u8], cursor: &mut usize) -> Option<&'buf [u8]> {
    if buf.len() < *cursor + 2 {
        return None;
    }
    let len = u16::from_be_bytes([buf[*cursor], buf[*cursor + 1]]) as usize;
    *cursor += 2;
    if buf.len() < *cursor + len {
        return None;
    }
    let out = &buf[*cursor..*cursor + len];
    *cursor += len;
    Some(out)
}

/// `symbols_by_path`: `u16:len(rel) ‖ rel ‖ start_byte:u32_be`.
pub fn symbol_by_path(rel: &RelPath, start_byte: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len() + 4);
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out.extend_from_slice(&start_byte.to_be_bytes());
    out
}

/// Prefix bytes for "all symbols in this file" — feed to `keyspace.prefix(..)`.
pub fn symbols_by_path_prefix(rel: &RelPath) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len());
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out
}

pub fn parse_symbol_by_path(key: &[u8]) -> Option<(RelPath, u32)> {
    let mut c = 0;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((RelPath::from(rel), start))
}

/// `symbols_by_name`: `u16:len(name) ‖ name ‖ kind:u8 ‖ u16:len(rel) ‖ rel ‖ start_byte:u32_be`.
///
/// Returns `None` when `name` exceeds 65535 bytes. The caller skips the secondary-index
/// entry but still writes the primary `symbols_by_path` entry so the outline stays complete.
pub fn symbol_by_name(name: &str, kind: SymbolKind, rel: &RelPath, start_byte: u32) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + name.len() + 1 + 2 + rel.as_bytes().len() + 4);
    write_len_prefixed(&mut out, name.as_bytes())?;
    out.push(symbol_kind_byte(kind));
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out.extend_from_slice(&start_byte.to_be_bytes());
    Some(out)
}

pub fn symbols_by_name_prefix(name: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + name.len());
    let _ = write_len_prefixed(&mut out, name.as_bytes());
    out
}

pub fn parse_symbol_by_name(key: &[u8]) -> Option<(String, SymbolKind, RelPath, u32)> {
    let mut c = 0;
    let name_bytes = read_len_prefixed(key, &mut c)?;
    let name = String::from_utf8(name_bytes).ok()?;
    if key.len() < c + 1 {
        return None;
    }
    let kind = symbol_kind_from_byte(key[c]);
    c += 1;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((name, kind, RelPath::from(rel), start))
}

/// `calls_by_callee`: `u16:len(callee) ‖ callee ‖ u16:len(rel) ‖ rel ‖ start_byte:u32_be`.
///
/// Returns `None` when `callee` exceeds 65535 bytes. The caller skips the secondary-index
/// entry but still writes the primary `calls_by_path` entry so the call record stays complete.
pub fn call_by_callee(callee: &str, rel: &RelPath, start_byte: u32) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + callee.len() + 2 + rel.as_bytes().len() + 4);
    write_len_prefixed(&mut out, callee.as_bytes())?;
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out.extend_from_slice(&start_byte.to_be_bytes());
    Some(out)
}

pub fn calls_by_callee_prefix(callee: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + callee.len());
    let _ = write_len_prefixed(&mut out, callee.as_bytes());
    out
}

pub fn parse_call_by_callee(key: &[u8]) -> Option<(String, RelPath, u32)> {
    let mut c = 0;
    let callee = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((callee, RelPath::from(rel), start))
}

/// `calls_by_path`: same shape as `symbols_by_path` so iterating "all calls in this file"
/// works the same way.
pub fn call_by_path(rel: &RelPath, start_byte: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len() + 4);
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out.extend_from_slice(&start_byte.to_be_bytes());
    out
}

pub fn calls_by_path_prefix(rel: &RelPath) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len());
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out
}

/// `imports_by_module`: `u16:len(module) ‖ module ‖ u16:len(rel) ‖ rel ‖ start_byte:u32_be`.
///
/// Returns `None` when `module` exceeds 65535 bytes. The caller skips the secondary-index
/// entry but still writes the primary `imports_by_path` entry so the import record stays complete.
pub fn import_by_module(module: &str, rel: &RelPath, start_byte: u32) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + module.len() + 2 + rel.as_bytes().len() + 4);
    write_len_prefixed(&mut out, module.as_bytes())?;
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out.extend_from_slice(&start_byte.to_be_bytes());
    Some(out)
}

pub fn imports_by_module_prefix(module: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + module.len());
    let _ = write_len_prefixed(&mut out, module.as_bytes());
    out
}

pub fn parse_import_by_module(key: &[u8]) -> Option<(String, RelPath, u32)> {
    let mut c = 0;
    let module = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((module, RelPath::from(rel), start))
}

/// `imports_by_path`: same role as `symbols_by_path` for the imports keyspace —
/// gives O(prefix) deletion when re-upserting a file. Shape:
/// `u16:len(rel) ‖ rel ‖ u16:len(module) ‖ module ‖ start_byte:u32_be`.
///
/// Returns `None` when `module` exceeds 65535 bytes. The rel component is path-only
/// and never reaches the 64 KiB ceiling.
pub fn import_by_path(rel: &RelPath, module: &str, start_byte: u32) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len() + 2 + module.len() + 4);
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    write_len_prefixed(&mut out, module.as_bytes())?;
    out.extend_from_slice(&start_byte.to_be_bytes());
    Some(out)
}

pub fn imports_by_path_prefix(rel: &RelPath) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len());
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out
}

pub fn parse_import_by_path(key: &[u8]) -> Option<(RelPath, String, u32)> {
    let mut c = 0;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    let module = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((RelPath::from(rel), module, start))
}

/// `implementations_by_trait`: prefix-scan keyspace for `find_implementations`. Shape:
/// `u16:len(trait_name) ‖ trait_name ‖ u16:len(impl_type) ‖ impl_type ‖
/// u16:len(rel) ‖ rel ‖ start_byte:u32_be`.
///
/// Returns `None` when `trait_name` or `impl_type` exceeds 65535 bytes. The caller skips
/// the secondary-index entry but still writes the primary `implementations_by_path` entry.
pub fn impl_by_trait(trait_name: &str, impl_type: &str, rel: &RelPath, start_byte: u32) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + trait_name.len() + 2 + impl_type.len() + 2 + rel.as_bytes().len() + 4);
    write_len_prefixed(&mut out, trait_name.as_bytes())?;
    write_len_prefixed(&mut out, impl_type.as_bytes())?;
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out.extend_from_slice(&start_byte.to_be_bytes());
    Some(out)
}

pub fn impls_by_trait_prefix(trait_name: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + trait_name.len());
    let _ = write_len_prefixed(&mut out, trait_name.as_bytes());
    out
}

pub fn parse_impl_by_trait(key: &[u8]) -> Option<(String, String, RelPath, u32)> {
    let mut c = 0;
    let trait_name = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    let impl_type = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((trait_name, impl_type, RelPath::from(rel), start))
}

/// `implementations_by_path`: companion partition keyed by file so the per-file delete on
/// upsert is O(prefix) instead of a full-iter scan. Shape:
/// `u16:len(rel) ‖ rel ‖ u16:len(trait_name) ‖ trait_name ‖
/// u16:len(impl_type) ‖ impl_type ‖ start_byte:u32_be`.
///
/// Returns `None` when `trait_name` or `impl_type` exceeds 65535 bytes. The rel component
/// is path-only and never reaches the 64 KiB ceiling.
pub fn impl_by_path(rel: &RelPath, trait_name: &str, impl_type: &str, start_byte: u32) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len() + 2 + trait_name.len() + 2 + impl_type.len() + 4);
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    write_len_prefixed(&mut out, trait_name.as_bytes())?;
    write_len_prefixed(&mut out, impl_type.as_bytes())?;
    out.extend_from_slice(&start_byte.to_be_bytes());
    Some(out)
}

pub fn impls_by_path_prefix(rel: &RelPath) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len());
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out
}

pub fn parse_impl_by_path(key: &[u8]) -> Option<(RelPath, String, String, u32)> {
    let mut c = 0;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    let trait_name = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    let impl_type = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    if key.len() < c + 4 {
        return None;
    }
    let start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((RelPath::from(rel), trait_name, impl_type, start))
}

// ─── resolved references (code-intelligence tier) ───────────────────────────

/// `refs_by_def`: resolved "references to a definition", prefix-scannable by the defining site.
/// Shape:
/// `u16:len(def_path) ‖ def_path ‖ def_start:u32_be ‖ u16:len(use_path) ‖ use_path ‖ use_start:u32_be`.
///
/// A [`refs_by_def_prefix`] range scan over `(def_path, def_start)` returns every use resolved to
/// that definition — the scope/import-resolved backing for `find_references` / `find_callers`.
/// Both endpoints are byte offsets; the def and use paths may differ (cross-file edge).
pub fn ref_by_def(def_path: &RelPath, def_start: u32, use_path: &RelPath, use_start: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + def_path.as_bytes().len() + 4 + 2 + use_path.as_bytes().len() + 4);
    let _ = write_len_prefixed(&mut out, def_path.as_bytes());
    out.extend_from_slice(&def_start.to_be_bytes());
    let _ = write_len_prefixed(&mut out, use_path.as_bytes());
    out.extend_from_slice(&use_start.to_be_bytes());
    out
}

/// Prefix bytes for "all references to the definition at `(def_path, def_start)`".
pub fn refs_by_def_prefix(def_path: &RelPath, def_start: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + def_path.as_bytes().len() + 4);
    let _ = write_len_prefixed(&mut out, def_path.as_bytes());
    out.extend_from_slice(&def_start.to_be_bytes());
    out
}

pub fn parse_ref_by_def(key: &[u8]) -> Option<(RelPath, u32, RelPath, u32)> {
    let mut c = 0;
    let def_path = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let def_start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    c += 4;
    let use_path = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let use_start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((RelPath::from(def_path), def_start, RelPath::from(use_path), use_start))
}

/// `refs_by_path`: companion keyed by the USE file. Serves two roles — O(prefix) delete of a
/// file's resolved edges on re-resolve, and the forward lookup that backs `goto_definition`
/// (a use position → its definition). Shape:
/// `u16:len(use_path) ‖ use_path ‖ use_start:u32_be ‖ u16:len(def_path) ‖ def_path ‖ def_start:u32_be`.
pub fn ref_by_path(use_path: &RelPath, use_start: u32, def_path: &RelPath, def_start: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + use_path.as_bytes().len() + 4 + 2 + def_path.as_bytes().len() + 4);
    let _ = write_len_prefixed(&mut out, use_path.as_bytes());
    out.extend_from_slice(&use_start.to_be_bytes());
    let _ = write_len_prefixed(&mut out, def_path.as_bytes());
    out.extend_from_slice(&def_start.to_be_bytes());
    out
}

/// Prefix bytes for "every resolved edge whose use is in this file" — used for the per-file
/// delete on re-resolve.
pub fn refs_by_path_prefix(use_path: &RelPath) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + use_path.as_bytes().len());
    let _ = write_len_prefixed(&mut out, use_path.as_bytes());
    out
}

/// Prefix bytes for "the definition of the use at `(use_path, use_start)`" — backs `goto_definition`.
pub fn refs_by_use_prefix(use_path: &RelPath, use_start: u32) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + use_path.as_bytes().len() + 4);
    let _ = write_len_prefixed(&mut out, use_path.as_bytes());
    out.extend_from_slice(&use_start.to_be_bytes());
    out
}

pub fn parse_ref_by_path(key: &[u8]) -> Option<(RelPath, u32, RelPath, u32)> {
    let mut c = 0;
    let use_path = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let use_start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    c += 4;
    let def_path = read_len_prefixed_ref(key, &mut c)?;
    if key.len() < c + 4 {
        return None;
    }
    let def_start = u32::from_be_bytes([key[c], key[c + 1], key[c + 2], key[c + 3]]);
    Some((RelPath::from(use_path), use_start, RelPath::from(def_path), def_start))
}

// ─── code-search BM25 keyword lane ───────────────────────────────────────────
//
// Two always-created keyspaces back the native BM25 keyword lane over code chunks
// (`code-search` feature). A "document" here is one code chunk, identified by its content-
// addressed `chunk_id` (`<source-hash-hex>:<ordinal>`).
//
// - `code_bm25_postings` (inverted): term → the chunks it appears in, with per-posting term
//   frequency and document length inlined so a single term-prefix scan yields everything the
//   scorer needs. The posting-list length IS the term's document frequency.
// - `code_bm25_by_path` (forward): file → its chunks' `(chunk_id, doclen, terms)`, so a re-scan
//   can reconstruct and remove the previous scan's postings in O(prefix), mirroring the
//   `calls_by_path` → `calls_by_callee` delete pattern.

/// `code_bm25_postings`: `u16:len(term) ‖ term ‖ u16:len(chunk_id) ‖ chunk_id`.
///
/// Returns `None` when `term` exceeds 65535 bytes (the BM25 tokenizer caps term length far below
/// this, so `None` is unreachable in practice — the guard mirrors the other identifier encoders so
/// a pathological token is skipped rather than panicking inside a rayon `par_iter`).
pub fn code_bm25_posting(term: &str, chunk_id: &str) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(2 + term.len() + 2 + chunk_id.len());
    write_len_prefixed(&mut out, term.as_bytes())?;
    let _ = write_len_prefixed(&mut out, chunk_id.as_bytes());
    Some(out)
}

/// Prefix bytes for "every chunk containing `term`" — feed to `keyspace.prefix(..)`.
pub fn code_bm25_postings_prefix(term: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + term.len());
    let _ = write_len_prefixed(&mut out, term.as_bytes());
    out
}

/// Decode the trailing `chunk_id` from a `code_bm25_postings` key, skipping the (known-from-prefix)
/// term without allocating it. Returns a borrowed slice into `key`.
pub fn parse_code_bm25_posting_chunk_id(key: &[u8]) -> Option<&str> {
    let mut c = 0;
    read_len_prefixed_ref(key, &mut c)?; // skip term
    let chunk_id = read_len_prefixed_ref(key, &mut c)?;
    std::str::from_utf8(chunk_id).ok()
}

/// Decode `(term, chunk_id)` from a raw `code_bm25_postings` key. The allocating companion to
/// [`parse_code_bm25_posting_chunk_id`]; used by the roundtrip tests.
pub fn parse_code_bm25_posting(key: &[u8]) -> Option<(String, String)> {
    let mut c = 0;
    let term = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    let chunk_id = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    Some((term, chunk_id))
}

/// Encode a `code_bm25_postings` value: `tf:u32_be ‖ doclen:u32_be`. Both inlined so a single
/// term-prefix scan carries the term frequency and the document length the scorer needs.
pub fn code_bm25_posting_value(tf: u32, doclen: u32) -> [u8; 8] {
    let mut out = [0u8; 8];
    out[..4].copy_from_slice(&tf.to_be_bytes());
    out[4..].copy_from_slice(&doclen.to_be_bytes());
    out
}

/// Decode `(tf, doclen)` from a `code_bm25_postings` value.
pub fn parse_code_bm25_posting_value(value: &[u8]) -> Option<(u32, u32)> {
    if value.len() < 8 {
        return None;
    }
    let tf = u32::from_be_bytes([value[0], value[1], value[2], value[3]]);
    let doclen = u32::from_be_bytes([value[4], value[5], value[6], value[7]]);
    Some((tf, doclen))
}

/// `code_bm25_by_path`: `u16:len(rel) ‖ rel ‖ u16:len(chunk_id) ‖ chunk_id`. The forward map keyed
/// by file so re-scan deletion is O(prefix). Both components are path/hash-shaped and never reach
/// the 64 KiB ceiling.
pub fn code_bm25_by_path(rel: &RelPath, chunk_id: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len() + 2 + chunk_id.len());
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    let _ = write_len_prefixed(&mut out, chunk_id.as_bytes());
    out
}

/// Prefix bytes for "every BM25 chunk entry in this file" — used for the per-file delete on re-scan.
pub fn code_bm25_by_path_prefix(rel: &RelPath) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + rel.as_bytes().len());
    let _ = write_len_prefixed(&mut out, rel.as_bytes());
    out
}

pub fn parse_code_bm25_by_path(key: &[u8]) -> Option<(RelPath, String)> {
    let mut c = 0;
    let rel = read_len_prefixed_ref(key, &mut c)?;
    let chunk_id = String::from_utf8(read_len_prefixed(key, &mut c)?).ok()?;
    Some((RelPath::from(rel), chunk_id))
}

// ─── memory_by_key ───────────────────────────────────────────────────────────

/// Visibility ordinal for the **group** (shared) memory tier. Stable, append-only.
pub const MEMORY_VIS_GROUP: u8 = 0;
/// Visibility ordinal for the **individual** (per-agent) memory tier. Stable, append-only.
pub const MEMORY_VIS_INDIVIDUAL: u8 = 1;

/// `memory_by_key`:
/// `u16:scope_len ‖ scope ‖ NUL ‖ vis_byte ‖ u16:owner_len ‖ owner ‖ NUL ‖ u16:key_len ‖ key`.
///
/// The `(scope, vis_byte, owner)` triple forms the namespace; placing it ahead of the key
/// keeps every namespace's keys contiguous, so a [`memory_by_key_ns_prefix`] range scan
/// returns exactly one namespace's entries. `vis_byte` is one of [`MEMORY_VIS_GROUP`] /
/// [`MEMORY_VIS_INDIVIDUAL`]. `owner` is the empty string for the group tier and the
/// validated `AgentId` for the individual tier (NUL-free by construction).
pub fn memory_by_key(scope: &str, vis_byte: u8, owner: &str, key: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + scope.len() + 1 + 1 + 2 + owner.len() + 1 + 2 + key.len());
    let _ = write_len_prefixed(&mut out, scope.as_bytes());
    out.push(0u8);
    out.push(vis_byte);
    let _ = write_len_prefixed(&mut out, owner.as_bytes());
    out.push(0u8);
    let _ = write_len_prefixed(&mut out, key.as_bytes());
    out
}

/// Prefix bytes for "all memory entries in this `(scope, vis_byte, owner)` namespace" —
/// everything up to and including the owner's NUL separator. Feed to `keyspace.prefix(..)`
/// or use as the lower bound of a range scan.
pub fn memory_by_key_ns_prefix(scope: &str, vis_byte: u8, owner: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + scope.len() + 1 + 1 + 2 + owner.len() + 1);
    let _ = write_len_prefixed(&mut out, scope.as_bytes());
    out.push(0u8);
    out.push(vis_byte);
    let _ = write_len_prefixed(&mut out, owner.as_bytes());
    out.push(0u8);
    out
}

/// Prefix bytes for "every memory entry in this `scope`" — across all visibility tiers and
/// owners. Because `scope` is length-prefixed, this prefix bounds exactly one scope's keys
/// (a longer scope encodes a different `u16` length, so no spillover). Used by the background
/// rescan audit to scope its scan to one repo without enumerating per-agent owners.
pub fn memory_scope_prefix(scope: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + scope.len() + 1);
    let _ = write_len_prefixed(&mut out, scope.as_bytes());
    out.push(0u8);
    out
}

/// Decode `(scope, vis_byte, owner, key)` from a raw `memory_by_key` key buffer.
pub fn parse_memory_by_key(buf: &[u8]) -> Option<(String, u8, String, String)> {
    let mut c = 0;
    let scope = String::from_utf8(read_len_prefixed(buf, &mut c)?).ok()?;
    if buf.len() <= c {
        return None;
    }
    c += 1; // skip NUL separator after scope
    if buf.len() <= c {
        return None;
    }
    let vis_byte = buf[c];
    c += 1;
    let owner = String::from_utf8(read_len_prefixed(buf, &mut c)?).ok()?;
    if buf.len() <= c {
        return None;
    }
    c += 1; // skip NUL separator after owner
    let key = String::from_utf8(read_len_prefixed(buf, &mut c)?).ok()?;
    Some((scope, vis_byte, owner, key))
}

/// Zero-copy decode of just the trailing `key` from a raw `memory_by_key` buffer, skipping the
/// scope/vis_byte/owner namespace prefix without allocating. Use on scan paths (e.g.
/// `memory_list`) that only need the key and discard the namespace components.
pub fn parse_memory_key_only(buf: &[u8]) -> Option<&str> {
    let mut c = 0;
    read_len_prefixed_ref(buf, &mut c)?; // skip scope
    c += 1; // NUL after scope
    if buf.len() <= c {
        return None;
    }
    c += 1; // vis_byte
    read_len_prefixed_ref(buf, &mut c)?; // skip owner
    if buf.len() <= c {
        return None;
    }
    c += 1; // NUL after owner
    let key = read_len_prefixed_ref(buf, &mut c)?;
    std::str::from_utf8(key).ok()
}

// ─── proposals ─────────────────────────────────────────────────────────────
//
// The `proposals` keyspace holds propose-don't-commit governance candidates (W11). Archived
// stale memories (W10) live in a separate `memory_archive` keyspace but reuse the
// `memory_by_key` encoder above — archive rows are keyed identically to their live form.

/// Proposal kind ordinal for a **memory** candidate. Stable, append-only.
pub const PROPOSAL_KIND_MEMORY: u8 = 0;
/// Proposal kind ordinal for a **skill** candidate (co-change association-rule). Stable, append-only.
pub const PROPOSAL_KIND_SKILL: u8 = 1;
/// Tombstone kind — written when a proposal is rejected so re-mining cannot resurface it.
/// Value bytes are empty (marker only). Stable, append-only.
pub const PROPOSAL_KIND_TOMBSTONE: u8 = 2;

/// `proposal_by_id`: `u16:scope_len ‖ scope ‖ NUL ‖ kind_byte ‖ u16:id_len ‖ id`.
///
/// `(scope, kind_byte)` is the namespace; `id` is the content-addressed proposal id (hex blake3
/// of the normalized candidate) so re-mining the same candidate overwrites rather than dupes.
/// Layout mirrors [`memory_by_key`]: the namespace prefix sorts contiguously, so a
/// [`proposal_ns_prefix`] range scan returns exactly one `(scope, kind)` namespace.
pub fn proposal_by_id(scope: &str, kind_byte: u8, id: &str) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + scope.len() + 1 + 1 + 2 + id.len());
    let _ = write_len_prefixed(&mut out, scope.as_bytes());
    out.push(0u8);
    out.push(kind_byte);
    let _ = write_len_prefixed(&mut out, id.as_bytes());
    out
}

/// Prefix bytes for "all proposals in this `(scope, kind_byte)` namespace" — feed to a range scan.
pub fn proposal_ns_prefix(scope: &str, kind_byte: u8) -> Vec<u8> {
    let mut out = Vec::with_capacity(2 + scope.len() + 1 + 1);
    let _ = write_len_prefixed(&mut out, scope.as_bytes());
    out.push(0u8);
    out.push(kind_byte);
    out
}

/// Decode `(scope, kind_byte, id)` from a raw `proposal_by_id` key buffer.
pub fn parse_proposal_by_id(buf: &[u8]) -> Option<(String, u8, String)> {
    let mut c = 0;
    let scope = String::from_utf8(read_len_prefixed(buf, &mut c)?).ok()?;
    if buf.len() <= c {
        return None;
    }
    c += 1; // skip NUL separator after scope
    if buf.len() <= c {
        return None;
    }
    let kind_byte = buf[c];
    c += 1;
    let id = String::from_utf8(read_len_prefixed(buf, &mut c)?).ok()?;
    Some((scope, kind_byte, id))
}

/// One-byte ordinal for a `SymbolKind`. Stable across releases so existing keys stay valid;
/// new variants extend the tail. Keep the explicit assignments — accidentally reordering
/// would silently miscategorize cached entries.
fn symbol_kind_byte(k: SymbolKind) -> u8 {
    match k {
        SymbolKind::Unknown => 0,
        SymbolKind::Function => 1,
        SymbolKind::Method => 2,
        SymbolKind::Struct => 3,
        SymbolKind::Enum => 4,
        SymbolKind::Class => 5,
        SymbolKind::Interface => 6,
        SymbolKind::Trait => 7,
        SymbolKind::Type => 8,
        SymbolKind::Const => 9,
        SymbolKind::Module => 10,
        SymbolKind::Macro => 11,
        SymbolKind::Impl => 12,
        SymbolKind::Namespace => 13,
        SymbolKind::Getter => 14,
        SymbolKind::Setter => 15,
        // Append-only past this line — see `index-keyspace-evolution` skill.
        SymbolKind::Field => 16,
        SymbolKind::Variable => 17,
        SymbolKind::EnumVariant => 18,
        SymbolKind::Constructor => 19,
        SymbolKind::Decorator => 20,
        SymbolKind::Heading => 21,
    }
}

fn symbol_kind_from_byte(b: u8) -> SymbolKind {
    match b {
        1 => SymbolKind::Function,
        2 => SymbolKind::Method,
        3 => SymbolKind::Struct,
        4 => SymbolKind::Enum,
        5 => SymbolKind::Class,
        6 => SymbolKind::Interface,
        7 => SymbolKind::Trait,
        8 => SymbolKind::Type,
        9 => SymbolKind::Const,
        10 => SymbolKind::Module,
        11 => SymbolKind::Macro,
        12 => SymbolKind::Impl,
        13 => SymbolKind::Namespace,
        14 => SymbolKind::Getter,
        15 => SymbolKind::Setter,
        16 => SymbolKind::Field,
        17 => SymbolKind::Variable,
        18 => SymbolKind::EnumVariant,
        19 => SymbolKind::Constructor,
        20 => SymbolKind::Decorator,
        21 => SymbolKind::Heading,
        _ => SymbolKind::Unknown,
    }
}

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

    #[test]
    fn symbol_by_path_roundtrips() {
        let rel = RelPath::from("src/lib.rs");
        let key = symbol_by_path(&rel, 1234);
        let (back, start) = parse_symbol_by_path(&key).unwrap();
        assert_eq!(back, rel);
        assert_eq!(start, 1234);
    }

    #[test]
    fn symbol_by_name_roundtrips_with_kind() {
        let rel = RelPath::from("src/foo.rs");
        let key = symbol_by_name("alpha", SymbolKind::Function, &rel, 42).unwrap();
        let (name, kind, back, start) = parse_symbol_by_name(&key).unwrap();
        assert_eq!(name, "alpha");
        assert_eq!(kind, SymbolKind::Function);
        assert_eq!(back, rel);
        assert_eq!(start, 42);
    }

    #[test]
    fn call_by_callee_roundtrips() {
        let rel = RelPath::from("src/main.rs");
        let key = call_by_callee("spawn", &rel, 999).unwrap();
        let (callee, back, start) = parse_call_by_callee(&key).unwrap();
        assert_eq!(callee, "spawn");
        assert_eq!(back, rel);
        assert_eq!(start, 999);
    }

    #[test]
    fn import_by_module_roundtrips() {
        let rel = RelPath::from("src/foo.py");
        let key = import_by_module("os.path", &rel, 0).unwrap();
        let (module, back, start) = parse_import_by_module(&key).unwrap();
        assert_eq!(module, "os.path");
        assert_eq!(back, rel);
        assert_eq!(start, 0);
    }

    /// The whole point of length-prefixing: `Foo` and `Foobar` must never collide on
    /// a prefix scan of `Foo`. Without length-prefixing, the simple `\0` separator would
    /// fail for callee names containing embedded `\0` bytes (rare but possible).
    #[test]
    fn prefix_scan_isolates_callees() {
        let rel = RelPath::from("a.rs");
        let key_foo = call_by_callee("Foo", &rel, 1).unwrap();
        let key_foobar = call_by_callee("Foobar", &rel, 1).unwrap();
        let prefix_foo = calls_by_callee_prefix("Foo");
        assert!(key_foo.starts_with(&prefix_foo), "Foo's key must extend the Foo prefix");
        assert!(
            !key_foobar.starts_with(&prefix_foo),
            "Foobar's key must NOT match the Foo prefix"
        );
    }

    #[test]
    fn import_by_path_roundtrips() {
        let rel = RelPath::from("src/foo.py");
        let key = import_by_path(&rel, "os.path", 42).unwrap();
        let (back_rel, module, start) = parse_import_by_path(&key).unwrap();
        assert_eq!(back_rel, rel);
        assert_eq!(module, "os.path");
        assert_eq!(start, 42);
    }

    /// `imports_by_path` prefix scan must isolate one file's entries from another file
    /// whose path shares a leading substring (e.g. `src/foo.py` vs `src/foo.py.bak`).
    #[test]
    fn prefix_scan_isolates_imports_by_path() {
        let rel_a = RelPath::from("src/foo.py");
        let rel_b = RelPath::from("src/foo.py.bak");
        let key_a = import_by_path(&rel_a, "os", 0).unwrap();
        let key_b = import_by_path(&rel_b, "os", 0).unwrap();
        let prefix_a = imports_by_path_prefix(&rel_a);
        assert!(key_a.starts_with(&prefix_a), "rel_a's key must extend rel_a's prefix");
        assert!(
            !key_b.starts_with(&prefix_a),
            "rel_b's key must NOT match rel_a's prefix"
        );
    }

    #[test]
    fn impl_by_trait_roundtrips() {
        let rel = RelPath::from("src/foo.rs");
        let key = impl_by_trait("Display", "Foo", &rel, 42).unwrap();
        let (trait_name, impl_type, back_rel, start) = parse_impl_by_trait(&key).unwrap();
        assert_eq!(trait_name, "Display");
        assert_eq!(impl_type, "Foo");
        assert_eq!(back_rel, rel);
        assert_eq!(start, 42);
    }

    #[test]
    fn impl_by_path_roundtrips() {
        let rel = RelPath::from("src/foo.rs");
        let key = impl_by_path(&rel, "Display", "Foo", 42).unwrap();
        let (back_rel, trait_name, impl_type, start) = parse_impl_by_path(&key).unwrap();
        assert_eq!(back_rel, rel);
        assert_eq!(trait_name, "Display");
        assert_eq!(impl_type, "Foo");
        assert_eq!(start, 42);
    }

    /// Prefix scan for `Display` must not bleed into `DisplayFmt`.
    #[test]
    fn prefix_scan_isolates_impls_by_trait() {
        let rel = RelPath::from("a.rs");
        let key_a = impl_by_trait("Display", "Foo", &rel, 1).unwrap();
        let key_b = impl_by_trait("DisplayFmt", "Foo", &rel, 1).unwrap();
        let prefix = impls_by_trait_prefix("Display");
        assert!(
            key_a.starts_with(&prefix),
            "Display's key must extend the Display prefix"
        );
        assert!(
            !key_b.starts_with(&prefix),
            "DisplayFmt's key must NOT match the Display prefix"
        );
    }

    /// `impls_by_path` prefix scan must isolate one file's entries from another file whose
    /// path shares a leading substring (e.g. `src/foo.rs` vs `src/foo.rs.bak`).
    #[test]
    fn prefix_scan_isolates_impls_by_path() {
        let rel_a = RelPath::from("src/foo.rs");
        let rel_b = RelPath::from("src/foo.rs.bak");
        let key_a = impl_by_path(&rel_a, "Display", "Foo", 0).unwrap();
        let key_b = impl_by_path(&rel_b, "Display", "Foo", 0).unwrap();
        let prefix_a = impls_by_path_prefix(&rel_a);
        assert!(key_a.starts_with(&prefix_a), "rel_a's key must extend rel_a's prefix");
        assert!(
            !key_b.starts_with(&prefix_a),
            "rel_b's key must NOT match rel_a's prefix"
        );
    }

    #[test]
    fn ref_by_def_roundtrips() {
        let def = RelPath::from("src/util.ts");
        let usef = RelPath::from("src/app.ts");
        let key = ref_by_def(&def, 100, &usef, 250);
        let (back_def, def_start, back_use, use_start) = parse_ref_by_def(&key).unwrap();
        assert_eq!(back_def, def);
        assert_eq!(def_start, 100);
        assert_eq!(back_use, usef);
        assert_eq!(use_start, 250);
    }

    #[test]
    fn ref_by_path_roundtrips() {
        let usef = RelPath::from("src/app.ts");
        let def = RelPath::from("src/util.ts");
        let key = ref_by_path(&usef, 250, &def, 100);
        let (back_use, use_start, back_def, def_start) = parse_ref_by_path(&key).unwrap();
        assert_eq!(back_use, usef);
        assert_eq!(use_start, 250);
        assert_eq!(back_def, def);
        assert_eq!(def_start, 100);
    }

    /// A `refs_by_def` scan for the definition at `(path, 100)` must not bleed into a
    /// definition at `(path, 1000)` in the same file — the `u32` def offset disambiguates.
    #[test]
    fn refs_by_def_prefix_isolates_definitions() {
        let def = RelPath::from("src/util.ts");
        let usef = RelPath::from("src/app.ts");
        let key_100 = ref_by_def(&def, 100, &usef, 5);
        let key_1000 = ref_by_def(&def, 1000, &usef, 5);
        let prefix_100 = refs_by_def_prefix(&def, 100);
        assert!(
            key_100.starts_with(&prefix_100),
            "def@100's edge must extend the def@100 prefix"
        );
        assert!(
            !key_1000.starts_with(&prefix_100),
            "def@1000's edge must NOT match the def@100 prefix"
        );
    }

    /// A `refs_by_path` file-level prefix must isolate one use-file's edges from another whose
    /// path shares a leading substring; and the position-level prefix must pin one use site.
    #[test]
    fn refs_by_path_prefixes_isolate() {
        let use_a = RelPath::from("src/app.ts");
        let use_b = RelPath::from("src/app.ts.bak");
        let def = RelPath::from("src/util.ts");
        let key_a = ref_by_path(&use_a, 250, &def, 100);
        let key_b = ref_by_path(&use_b, 250, &def, 100);
        let file_prefix = refs_by_path_prefix(&use_a);
        assert!(
            key_a.starts_with(&file_prefix),
            "use_a's edge must extend use_a's file prefix"
        );
        assert!(
            !key_b.starts_with(&file_prefix),
            "use_b's edge must NOT match use_a's file prefix"
        );

        let use_prefix = refs_by_use_prefix(&use_a, 250);
        let key_other_pos = ref_by_path(&use_a, 9, &def, 100);
        assert!(
            key_a.starts_with(&use_prefix),
            "use@250 edge must extend the use@250 prefix"
        );
        assert!(
            !key_other_pos.starts_with(&use_prefix),
            "a different use offset must NOT match the use@250 prefix"
        );
    }

    #[test]
    fn non_utf8_path_keys_roundtrip() {
        let rel = RelPath::from(b"f\xffoo.rs".as_slice());
        let key = symbol_by_path(&rel, 7);
        let (back, _) = parse_symbol_by_path(&key).unwrap();
        assert_eq!(back.as_bytes(), rel.as_bytes());
    }

    #[test]
    fn symbol_kind_byte_roundtrip_all_variants() {
        let all = [
            SymbolKind::Unknown,
            SymbolKind::Function,
            SymbolKind::Method,
            SymbolKind::Struct,
            SymbolKind::Enum,
            SymbolKind::Class,
            SymbolKind::Interface,
            SymbolKind::Trait,
            SymbolKind::Type,
            SymbolKind::Const,
            SymbolKind::Module,
            SymbolKind::Macro,
            SymbolKind::Impl,
            SymbolKind::Namespace,
            SymbolKind::Getter,
            SymbolKind::Setter,
        ];
        for k in all {
            assert_eq!(symbol_kind_from_byte(symbol_kind_byte(k)), k);
        }
    }

    /// All six identifier-encoding functions must return `None` at the 65536-byte boundary
    /// rather than panicking. This protects the rayon `par_iter` scan from being aborted
    /// by a single pathologically long token.
    #[test]
    fn oversized_identifier_returns_none() {
        let huge = "x".repeat(65536);
        let rel = RelPath::from("a.rs");

        assert!(
            symbol_by_name(&huge, SymbolKind::Function, &rel, 0).is_none(),
            "symbol_by_name must return None for a 65536-byte name"
        );
        assert!(
            call_by_callee(&huge, &rel, 0).is_none(),
            "call_by_callee must return None for a 65536-byte callee"
        );
        assert!(
            import_by_module(&huge, &rel, 0).is_none(),
            "import_by_module must return None for a 65536-byte module"
        );
        assert!(
            import_by_path(&rel, &huge, 0).is_none(),
            "import_by_path must return None for a 65536-byte module"
        );
        assert!(
            impl_by_trait(&huge, "T", &rel, 0).is_none(),
            "impl_by_trait must return None for a 65536-byte trait name"
        );
        assert!(
            impl_by_path(&rel, &huge, "T", 0).is_none(),
            "impl_by_path must return None for a 65536-byte trait name"
        );
    }

    #[test]
    fn memory_by_key_roundtrips_group() {
        let raw = memory_by_key("scope-a", MEMORY_VIS_GROUP, "", "my.key");
        assert_eq!(
            parse_memory_by_key(&raw),
            Some((
                "scope-a".to_string(),
                MEMORY_VIS_GROUP,
                String::new(),
                "my.key".to_string()
            ))
        );
    }

    #[test]
    fn memory_by_key_roundtrips_individual() {
        let raw = memory_by_key("scope-a", MEMORY_VIS_INDIVIDUAL, "agent-7", "my.key");
        assert_eq!(
            parse_memory_by_key(&raw),
            Some((
                "scope-a".to_string(),
                MEMORY_VIS_INDIVIDUAL,
                "agent-7".to_string(),
                "my.key".to_string()
            ))
        );
    }

    /// The zero-copy `parse_memory_key_only` must return exactly the `key` component that the
    /// allocating `parse_memory_by_key` yields, for every namespace shape — including keys whose
    /// own bytes contain the NUL-adjacent separators and length-prefix-sized values.
    #[test]
    fn parse_memory_key_only_matches_full_parse() {
        let cases = [
            ("scope-a", MEMORY_VIS_GROUP, "", "my.key"),
            ("scope-a", MEMORY_VIS_INDIVIDUAL, "agent-7", "ns:sub.key"),
            ("", MEMORY_VIS_GROUP, "", ""),
            ("s", MEMORY_VIS_INDIVIDUAL, "owner-with-dashes", "k"),
            ("scope/with/slashes", MEMORY_VIS_GROUP, "", "key.with.many.dots"),
        ];
        for (scope, vis, owner, key) in cases {
            let raw = memory_by_key(scope, vis, owner, key);
            let full = parse_memory_by_key(&raw).map(|(_, _, _, k)| k);
            let only = parse_memory_key_only(&raw).map(str::to_string);
            assert_eq!(only, full, "key-only parse diverged for key {key:?}");
            assert_eq!(only.as_deref(), Some(key));
        }
    }

    #[test]
    fn parse_memory_key_only_rejects_truncated_buffer() {
        let raw = memory_by_key("scope-a", MEMORY_VIS_INDIVIDUAL, "agent-7", "my.key");
        // Lop off the trailing key bytes: the length prefix promises more than remains.
        assert_eq!(parse_memory_key_only(&raw[..raw.len() - 3]), None);
        assert_eq!(parse_memory_key_only(&[]), None);
    }

    /// A group key and an individual key for the same `(scope, key)` must live in
    /// disjoint namespaces: neither key may fall within the other's namespace prefix.
    #[test]
    fn memory_namespace_prefixes_do_not_overlap() {
        let scope = "scope-a";
        let key = "shared.key";
        let group_key = memory_by_key(scope, MEMORY_VIS_GROUP, "", key);
        let indiv_key = memory_by_key(scope, MEMORY_VIS_INDIVIDUAL, "agent-7", key);

        let group_prefix = memory_by_key_ns_prefix(scope, MEMORY_VIS_GROUP, "");
        let indiv_prefix = memory_by_key_ns_prefix(scope, MEMORY_VIS_INDIVIDUAL, "agent-7");

        assert!(
            group_key.starts_with(&group_prefix),
            "group key must extend the group namespace prefix"
        );
        assert!(
            indiv_key.starts_with(&indiv_prefix),
            "individual key must extend the individual namespace prefix"
        );
        assert!(
            !group_key.starts_with(&indiv_prefix),
            "a group key must NOT fall within an individual namespace prefix"
        );
        assert!(
            !indiv_key.starts_with(&group_prefix),
            "an individual key must NOT fall within the group namespace prefix"
        );
    }

    #[test]
    fn code_bm25_posting_roundtrips() {
        let key = code_bm25_posting("spawn", "abcd1234:3").unwrap();
        let (term, chunk_id) = parse_code_bm25_posting(&key).unwrap();
        assert_eq!(term, "spawn");
        assert_eq!(chunk_id, "abcd1234:3");
        assert_eq!(parse_code_bm25_posting_chunk_id(&key), Some("abcd1234:3"));
    }

    #[test]
    fn code_bm25_posting_value_roundtrips() {
        let value = code_bm25_posting_value(7, 142);
        assert_eq!(parse_code_bm25_posting_value(&value), Some((7, 142)));
        assert_eq!(parse_code_bm25_posting_value(&value[..7]), None);
    }

    /// A `spawn` posting prefix must not bleed into `spawn_blocking` — the whole point of
    /// length-prefixing the term component.
    #[test]
    fn code_bm25_posting_prefix_isolates_terms() {
        let key_spawn = code_bm25_posting("spawn", "h:1").unwrap();
        let key_spawn_blocking = code_bm25_posting("spawnblocking", "h:1").unwrap();
        let prefix = code_bm25_postings_prefix("spawn");
        assert!(
            key_spawn.starts_with(&prefix),
            "spawn's key must extend the spawn prefix"
        );
        assert!(
            !key_spawn_blocking.starts_with(&prefix),
            "spawnblocking's key must NOT match the spawn prefix"
        );
    }

    #[test]
    fn code_bm25_by_path_roundtrips_and_isolates() {
        let rel_a = RelPath::from("src/foo.rs");
        let rel_b = RelPath::from("src/foo.rs.bak");
        let key = code_bm25_by_path(&rel_a, "hash:0");
        let (back, chunk_id) = parse_code_bm25_by_path(&key).unwrap();
        assert_eq!(back, rel_a);
        assert_eq!(chunk_id, "hash:0");

        let key_b = code_bm25_by_path(&rel_b, "hash:0");
        let prefix_a = code_bm25_by_path_prefix(&rel_a);
        assert!(key.starts_with(&prefix_a), "rel_a's key must extend rel_a's prefix");
        assert!(
            !key_b.starts_with(&prefix_a),
            "rel_b's key must NOT match rel_a's prefix"
        );
    }

    /// Two different agents' individual namespaces for the same scope+key are disjoint.
    #[test]
    fn memory_individual_namespaces_isolate_by_owner() {
        let scope = "scope-a";
        let key = "k";
        let a_key = memory_by_key(scope, MEMORY_VIS_INDIVIDUAL, "agent-a", key);
        let b_prefix = memory_by_key_ns_prefix(scope, MEMORY_VIS_INDIVIDUAL, "agent-b");
        assert!(
            !a_key.starts_with(&b_prefix),
            "agent-a's key must NOT fall within agent-b's namespace prefix"
        );
    }
}