instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
// generated by hxc 1.0.0-acgt-compiler from src/snapshot.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:5
use std::{
    collections::{BTreeMap, HashMap},
    fs,
    io::{Read, Write},
    path::{Path, PathBuf},
};
// hlx:6
use super::{eligibility::Meta, rehearsal::StandingInstruction, Discovery};
// hlx:8
pub(super) fn enabled() -> bool {
    // hlx:9
    std::env::var("INSTINCT_INDEX").map_or(true, |v| v != "0")
    // hlx:10
}
// hlx:13
fn feed(h: &mut [u64; 4], blocks: &[u8]) {
    // hlx:14
    for c in blocks.chunks_exact(32) {
        // hlx:15
        for j in 0..4 {
            // hlx:16
            let w = u64::from_le_bytes([
                c[j * 8],
                c[j * 8 + 1],
                c[j * 8 + 2],
                c[j * 8 + 3],
                c[j * 8 + 4],
                c[j * 8 + 5],
                c[j * 8 + 6],
                c[j * 8 + 7],
            ]);
            // hlx:17
            h[j] = (h[j].rotate_left(5) ^ w).wrapping_mul(0x517CC1B727220A95);
            // hlx:18
        }
        // hlx:19
    }
    // hlx:20
}
// hlx:22
fn seed() -> [u64; 4] {
    // hlx:23
    [
        0x9E3779B97F4A7C15,
        0xC2B2AE3D27D4EB4F,
        0x165667B19E3779F9,
        0x27D4EB2F165667C5,
    ]
    // hlx:24
}
// hlx:26
fn finish(mut h: [u64; 4], tail: &[u8], total: u64) -> (u64, u64) {
    // hlx:27
    let mut block = [0u8; 32];
    // hlx:28
    block[..tail.len()].copy_from_slice(tail);
    // hlx:29
    feed(&mut h, &block);
    // hlx:30
    h[0] ^= total;
    // hlx:31
    let mut a = (h[0] ^ h[1].rotate_left(17)).wrapping_mul(0xFF51AFD7ED558CCD);
    // hlx:32
    let mut b = (h[2] ^ h[3].rotate_left(23)).wrapping_mul(0xC4CEB9FE1A85EC53);
    // hlx:33
    a ^= a >> 32;
    // hlx:34
    b ^= b >> 29;
    // hlx:35
    (a, b)
    // hlx:36
}
// hlx:38
fn mix(bytes: &[u8]) -> (u64, u64) {
    // hlx:39
    let mut h = seed();
    // hlx:40
    let whole = bytes.len() - bytes.len() % 32;
    // hlx:41
    feed(&mut h, &bytes[..whole]);
    // hlx:42
    finish(h, &bytes[whole..], bytes.len() as u64)
    // hlx:43
}
// hlx:45
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
// hlx:46
pub(super) struct Key {
    // hlx:47
    len: u64,
    // hlx:48
    a: u64,
    // hlx:49
    b: u64,
    // hlx:50
    weights: [u8; 4],
    // hlx:51
}
// hlx:53
pub(super) fn key(path: &Path) -> Option<Key> {
    // hlx:54
    if !enabled() {
        // hlx:55
        return None;
        // hlx:56
    }
    // hlx:57
    let mut file = fs::File::open(path).ok()?;
    // hlx:58
    let mut buf = vec![0u8; 65536];
    // hlx:59
    let mut h = seed();
    // hlx:60
    let mut total = 0u64;
    // hlx:61
    let mut encoding = super::unicode_words::BankEncoding::default();
    // hlx:62
    let mut tail: Vec<u8> = Vec::new();
    // hlx:63
    for _ in 0..u64::MAX {
        // hlx:64
        let mut got = 0usize;
        // hlx:65
        for _ in 0..buf.len() {
            // hlx:66
            if got == buf.len() {
                // hlx:67
                break;
                // hlx:68
            }
            // hlx:69
            let n = file.read(&mut buf[got..]).ok()?;
            // hlx:70
            if n == 0 {
                // hlx:71
                break;
                // hlx:72
            }
            // hlx:73
            got += n;
            // hlx:74
        }
        // hlx:75
        encoding.feed(&buf[..got]);
        // hlx:76
        let whole = got - got % 32;
        // hlx:77
        feed(&mut h, &buf[..whole]);
        // hlx:78
        total += got as u64;
        // hlx:79
        if got < buf.len() {
            // hlx:80
            tail = buf[whole..got].to_vec();
            // hlx:81
            break;
            // hlx:82
        }
        // hlx:83
    }
    // hlx:84
    let (mut a, b) = finish(h, &tail, total);
    // hlx:86
    if encoding.unicode {
        // hlx:87
        a ^= 0x554E49434F444533;
        // hlx:88
    }
    // hlx:89
    let (w, t, body) = super::lex_weights();
    // hlx:90
    Some(Key {
        len: total,
        a,
        b,
        weights: [
            w as u8,
            t as u8,
            body as u8,
            super::concepts::enabled() as u8,
        ],
    })
    // hlx:91
}
// hlx:93
fn idx_path(path: &Path) -> PathBuf {
    // hlx:94
    let mut s = path.as_os_str().to_owned();
    // hlx:95
    s.push(".idx");
    // hlx:96
    PathBuf::from(s)
    // hlx:97
}
// hlx:99
fn put_u32(o: &mut Vec<u8>, v: u32) {
    // hlx:100
    o.extend_from_slice(&v.to_le_bytes())
    // hlx:101
}
// hlx:102
fn put_u64(o: &mut Vec<u8>, v: u64) {
    // hlx:103
    o.extend_from_slice(&v.to_le_bytes())
    // hlx:104
}
// hlx:105
fn put_str(o: &mut Vec<u8>, s: &str) {
    // hlx:106
    put_u32(o, s.len() as u32);
    // hlx:107
    o.extend_from_slice(s.as_bytes())
    // hlx:108
}
// hlx:110
fn header(key: &Key) -> Vec<u8> {
    // hlx:111
    let mut o = b"INSTIDX3".to_vec();
    // hlx:112
    put_str(&mut o, env!("CARGO_PKG_VERSION"));
    // hlx:113
    put_u64(&mut o, key.len);
    // hlx:114
    put_u64(&mut o, key.a);
    // hlx:115
    put_u64(&mut o, key.b);
    // hlx:116
    o.extend_from_slice(&key.weights);
    // hlx:117
    o
    // hlx:118
}
// hlx:120
fn put_entry(o: &mut Vec<u8>, d: &Discovery) {
    // hlx:121
    let at = o.len();
    // hlx:122
    put_u32(o, 0);
    // hlx:123
    for s in [
        &d.meta.source,
        &d.meta.state,
        &d.meta.evidence_status,
        &d.meta.project,
        &d.meta.persona,
        &d.meta.harness,
        &d.meta.version,
        &d.meta.machine,
    ] {
        // hlx:124
        put_str(o, s);
        // hlx:125
    }
    // hlx:126
    put_u64(o, d.meta.valid_until);
    // hlx:127
    for s in [
        &d.id,
        &d.title,
        &d.when,
        &d.found,
        &d.how,
        &d.evidence,
        &d.reconsider,
        &d.tags,
    ] {
        // hlx:128
        put_str(o, s);
        // hlx:129
    }
    // hlx:130
    put_u64(o, d.ts);
    // hlx:131
    put_u32(o, d.hits);
    // hlx:132
    put_u32(o, d.misses);
    // hlx:133
    put_u32(o, d.embedding.len() as u32);
    // hlx:134
    for f in &d.embedding {
        // hlx:135
        put_u32(o, f.to_bits());
        // hlx:136
    }
    // hlx:137
    if let Some(s) = &d.standing {
        // hlx:138
        o.push(1);
        // hlx:139
        put_str(o, &s.text);
        // hlx:140
        put_str(o, &s.reference);
        // hlx:141
    } else {
        // hlx:142
        o.push(0);
        // hlx:143
    }
    // hlx:144
    put_str(
        o,
        &d.casebook
            .as_ref()
            .map(|b| super::json_out(&b.to_json()))
            .unwrap_or_default(),
    );
    // hlx:145
    let len = (o.len() - at - 4) as u32;
    // hlx:146
    o[at..at + 4].copy_from_slice(&len.to_le_bytes());
    // hlx:147
}
// hlx:149
fn encode(key: &Key, all: &[Discovery]) -> Vec<u8> {
    // hlx:150
    let mut o = header(key);
    // hlx:151
    put_u32(&mut o, all.len() as u32);
    // hlx:152
    for d in all {
        // hlx:153
        put_entry(&mut o, d);
        // hlx:154
    }
    // hlx:155
    let mut lens: Vec<u32> = Vec::with_capacity(all.len());
    // hlx:156
    let mut vocab: BTreeMap<String, Vec<(u32, u32)>> = BTreeMap::new();
    // hlx:157
    for (i, d) in all.iter().enumerate() {
        // hlx:158
        let words = super::tokens(&d.lex_text());
        // hlx:159
        lens.push(words.len() as u32);
        // hlx:160
        let mut counts: HashMap<String, u32> = HashMap::new();
        // hlx:161
        for w in words {
            // hlx:162
            *counts.entry(w).or_insert(0) += 1;
            // hlx:163
        }
        // hlx:164
        for (w, tf) in counts {
            // hlx:165
            vocab.entry(w).or_default().push((i as u32, tf));
            // hlx:166
        }
        // hlx:167
    }
    // hlx:168
    for l in &lens {
        // hlx:169
        put_u32(&mut o, *l);
        // hlx:170
    }
    // hlx:171
    let mut blob: Vec<u8> = Vec::new();
    // hlx:172
    let mut voff: Vec<u32> = vec![0];
    // hlx:173
    let mut poff: Vec<u32> = vec![0];
    // hlx:174
    let mut pdoc: Vec<u32> = Vec::new();
    // hlx:175
    let mut ptf: Vec<u32> = Vec::new();
    // hlx:176
    for (w, list) in &vocab {
        // hlx:177
        blob.extend_from_slice(w.as_bytes());
        // hlx:178
        voff.push(blob.len() as u32);
        // hlx:179
        for &(doc, tf) in list {
            // hlx:180
            pdoc.push(doc);
            // hlx:181
            ptf.push(tf);
            // hlx:182
        }
        // hlx:183
        poff.push(pdoc.len() as u32);
        // hlx:184
    }
    // hlx:185
    put_u32(&mut o, vocab.len() as u32);
    // hlx:186
    for v in &voff {
        // hlx:187
        put_u32(&mut o, *v);
        // hlx:188
    }
    // hlx:189
    o.extend_from_slice(&blob);
    // hlx:190
    for v in poff.iter().chain(pdoc.iter()).chain(ptf.iter()) {
        // hlx:191
        put_u32(&mut o, *v);
        // hlx:192
    }
    // hlx:193
    let mut per: Vec<Vec<String>> = Vec::with_capacity(all.len());
    // hlx:194
    let mut avocab: BTreeMap<String, u32> = BTreeMap::new();
    // hlx:195
    for d in all {
        // hlx:196
        let mut seen = super::anchors(&d.when);
        // hlx:197
        seen.extend(super::anchors(&d.title));
        // hlx:198
        for t in d.tags.split(';') {
            // hlx:199
            seen.extend(super::anchors(t));
            // hlx:200
        }
        // hlx:201
        let mut v: Vec<String> = seen.into_iter().collect();
        // hlx:202
        v.sort();
        // hlx:203
        for a in &v {
            // hlx:204
            avocab.entry(a.clone()).or_insert(0);
            // hlx:205
        }
        // hlx:206
        per.push(v);
        // hlx:207
    }
    // hlx:208
    let idmap: HashMap<&str, u32> = avocab
        .keys()
        .enumerate()
        .map(|(i, s)| (s.as_str(), i as u32))
        .collect();
    // hlx:209
    put_u32(&mut o, avocab.len() as u32);
    // hlx:210
    let mut ablob: Vec<u8> = Vec::new();
    // hlx:211
    let mut aoff: Vec<u32> = vec![0];
    // hlx:212
    for s in avocab.keys() {
        // hlx:213
        ablob.extend_from_slice(s.as_bytes());
        // hlx:214
        aoff.push(ablob.len() as u32);
        // hlx:215
    }
    // hlx:216
    for v in &aoff {
        // hlx:217
        put_u32(&mut o, *v);
        // hlx:218
    }
    // hlx:219
    o.extend_from_slice(&ablob);
    // hlx:220
    let mut aloff: Vec<u32> = vec![0];
    // hlx:221
    let mut aids: Vec<u32> = Vec::new();
    // hlx:222
    for v in &per {
        // hlx:223
        for a in v {
            // hlx:224
            aids.push(idmap[a.as_str()]);
            // hlx:225
        }
        // hlx:226
        aloff.push(aids.len() as u32);
        // hlx:227
    }
    // hlx:228
    for v in aloff.iter().chain(aids.iter()) {
        // hlx:229
        put_u32(&mut o, *v);
        // hlx:230
    }
    // hlx:231
    let (a, b) = mix(&o);
    // hlx:232
    put_u64(&mut o, a);
    // hlx:233
    put_u64(&mut o, b);
    // hlx:234
    o
    // hlx:235
}
// hlx:238
fn check(buf: &[u8], key: &Key) -> Option<usize> {
    // hlx:239
    let n = buf.len().checked_sub(16)?;
    // hlx:240
    let (a, b) = mix(&buf[..n]);
    // hlx:241
    if buf[n..n + 8] != a.to_le_bytes() || buf[n + 8..] != b.to_le_bytes() {
        // hlx:242
        return None;
        // hlx:243
    }
    // hlx:244
    let h = header(key);
    // hlx:245
    if buf.get(..h.len()) != Some(&h[..]) {
        // hlx:246
        return None;
        // hlx:247
    }
    // hlx:248
    Some(n)
    // hlx:249
}
// hlx:252
pub(super) fn store(path: &Path, key: &Key, all: &[Discovery]) {
    // hlx:253
    if !enabled() {
        // hlx:254
        return;
        // hlx:255
    }
    // hlx:256
    let target = idx_path(path);
    // hlx:257
    if fs::read(&target)
        .ok()
        .is_some_and(|b| check(&b, key).is_some())
    {
        // hlx:258
        return;
        // hlx:259
    }
    // hlx:260
    if key_now(path) != Some(*key) {
        // hlx:261
        return;
        // hlx:262
    }
    // hlx:263
    let bytes = encode(key, all);
    // hlx:264
    let mut tmp = target.as_os_str().to_owned();
    // hlx:265
    tmp.push(format!(".tmp{}", std::process::id()));
    // hlx:266
    let tmp = PathBuf::from(tmp);
    // hlx:267
    let ok = super::journal::private_options()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&tmp)
        .and_then(|mut f| f.write_all(&bytes))
        .and_then(|_| fs::rename(&tmp, &target))
        .is_ok();
    // hlx:268
    if !ok {
        // hlx:269
        let _ = fs::remove_file(&tmp);
        // hlx:270
    }
    // hlx:271
}
// hlx:273
fn key_now(path: &Path) -> Option<Key> {
    // hlx:274
    key(path)
    // hlx:275
}
// hlx:277
struct Rd<'a> {
    b: &'a [u8],
    o: usize,
}
// hlx:278
fn take<'a>(r: &mut Rd<'a>, n: usize) -> Option<&'a [u8]> {
    // hlx:279
    let e = r.o.checked_add(n)?;
    // hlx:280
    let s = r.b.get(r.o..e)?;
    // hlx:281
    r.o = e;
    // hlx:282
    Some(s)
    // hlx:283
}
// hlx:284
fn r_u32(r: &mut Rd) -> Option<u32> {
    // hlx:285
    let s = take(r, 4)?;
    // hlx:286
    Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
    // hlx:287
}
// hlx:288
fn r_u64(r: &mut Rd) -> Option<u64> {
    // hlx:289
    let s = take(r, 8)?;
    // hlx:290
    Some(u64::from_le_bytes([
        s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],
    ]))
    // hlx:291
}
// hlx:292
fn r_str(r: &mut Rd) -> Option<String> {
    // hlx:293
    let n = r_u32(r)? as usize;
    // hlx:294
    String::from_utf8(take(r, n)?.to_vec()).ok()
    // hlx:295
}
// hlx:297
fn r_meta(r: &mut Rd) -> Option<Meta> {
    // hlx:298
    let source = r_str(r)?;
    // hlx:299
    let state = r_str(r)?;
    // hlx:300
    let evidence_status = r_str(r)?;
    // hlx:301
    let project = r_str(r)?;
    // hlx:302
    let persona = r_str(r)?;
    // hlx:303
    let harness = r_str(r)?;
    // hlx:304
    let version = r_str(r)?;
    // hlx:305
    let machine = r_str(r)?;
    // hlx:306
    let valid_until = r_u64(r)?;
    // hlx:307
    Some(Meta {
        source,
        state,
        evidence_status,
        project,
        persona,
        harness,
        version,
        machine,
        valid_until,
    })
    // hlx:308
}
// hlx:310
fn r_rest(r: &mut Rd, meta: Meta) -> Option<Discovery> {
    // hlx:311
    let id = r_str(r)?;
    // hlx:312
    let title = r_str(r)?;
    // hlx:313
    let when = r_str(r)?;
    // hlx:314
    let found = r_str(r)?;
    // hlx:315
    let how = r_str(r)?;
    // hlx:316
    let evidence = r_str(r)?;
    // hlx:317
    let reconsider = r_str(r)?;
    // hlx:318
    let tags = r_str(r)?;
    // hlx:319
    let ts = r_u64(r)?;
    // hlx:320
    let hits = r_u32(r)?;
    // hlx:321
    let misses = r_u32(r)?;
    // hlx:322
    let dims = r_u32(r)? as usize;
    // hlx:323
    let raw = take(r, dims.checked_mul(4)?)?;
    // hlx:324
    let embedding: Vec<f32> = raw
        .chunks_exact(4)
        .map(|c| f32::from_bits(u32::from_le_bytes([c[0], c[1], c[2], c[3]])))
        .collect();
    // hlx:325
    let standing = if take(r, 1)?[0] == 1 {
        Some(StandingInstruction {
            text: r_str(r)?,
            reference: r_str(r)?,
        })
    } else {
        None
    };
    // hlx:326
    let cases = r_str(r)?;
    // hlx:327
    let casebook = if cases.is_empty() {
        None
    } else {
        Some(super::case_learning::Casebook::parse(&super::parse_json(&cases).ok()?).ok()?)
    };
    // hlx:328
    Some(Discovery {
        id,
        ts,
        title,
        when,
        found,
        how,
        evidence,
        reconsider,
        tags,
        embedding,
        hits,
        misses,
        outcomes: HashMap::new(),
        standing,
        casebook,
        meta,
    })
    // hlx:329
}
// hlx:331
pub(super) struct Index {
    buf: Vec<u8>,
    lens: usize,
    vn: usize,
    voff: usize,
    vblob: usize,
    poff: usize,
    pdoc: usize,
    ptf: usize,
    avn: usize,
    aoff: usize,
    ablob: usize,
    aloff: usize,
    aids: usize,
}
// hlx:332
fn word(buf: &[u8], at: usize) -> usize {
    // hlx:333
    u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) as usize
    // hlx:334
}
// hlx:337
pub(super) fn open(
    path: &Path,
    key: &Key,
    scope: &super::eligibility::Scope,
    now: u64,
) -> Option<(Vec<Discovery>, Vec<u32>, Index)> {
    // hlx:338
    if !enabled() {
        // hlx:339
        return None;
        // hlx:340
    }
    // hlx:341
    let buf = fs::read(idx_path(path)).ok()?;
    // hlx:342
    let end = check(&buf, key)?;
    // hlx:343
    let mut r = Rd {
        b: &buf[..end],
        o: header(key).len(),
    };
    // hlx:344
    let n = r_u32(&mut r)? as usize;
    // hlx:345
    if n > end / 64 {
        // hlx:346
        return None;
        // hlx:347
    }
    // hlx:348
    let mut all = Vec::with_capacity(n);
    // hlx:349
    let mut pos = Vec::with_capacity(n);
    // hlx:350
    for _ in 0..n {
        // hlx:351
        let len = r_u32(&mut r)? as usize;
        // hlx:352
        let stop = r.o.checked_add(len)?;
        // hlx:353
        if stop > end {
            // hlx:354
            return None;
            // hlx:355
        }
        // hlx:356
        let meta = r_meta(&mut r)?;
        // hlx:357
        if super::eligibility::scope_check(&meta, scope, now).is_ok() {
            // hlx:358
            pos.push(all.len() as u32);
            // hlx:359
            all.push(r_rest(&mut r, meta)?);
            // hlx:360
        } else {
            // hlx:361
            pos.push(u32::MAX);
            // hlx:362
            r.o = stop;
            // hlx:363
        }
        // hlx:364
        if r.o != stop {
            // hlx:365
            return None;
            // hlx:366
        }
        // hlx:367
    }
    // hlx:368
    let lens = r.o;
    // hlx:369
    take(&mut r, n.checked_mul(4)?)?;
    // hlx:370
    let vn = r_u32(&mut r)? as usize;
    // hlx:371
    let voff = r.o;
    // hlx:372
    take(&mut r, vn.checked_add(1)?.checked_mul(4)?)?;
    // hlx:373
    let blob = word(&buf, voff + vn * 4);
    // hlx:374
    let vblob = r.o;
    // hlx:375
    take(&mut r, blob)?;
    // hlx:376
    let poff = r.o;
    // hlx:377
    take(&mut r, vn.checked_add(1)?.checked_mul(4)?)?;
    // hlx:378
    let total = word(&buf, poff + vn * 4);
    // hlx:379
    let pdoc = r.o;
    // hlx:380
    take(&mut r, total.checked_mul(4)?)?;
    // hlx:381
    let ptf = r.o;
    // hlx:382
    take(&mut r, total.checked_mul(4)?)?;
    // hlx:383
    let avn = r_u32(&mut r)? as usize;
    // hlx:384
    let aoff = r.o;
    // hlx:385
    take(&mut r, avn.checked_add(1)?.checked_mul(4)?)?;
    // hlx:386
    let ablob_len = word(&buf, aoff + avn * 4);
    // hlx:387
    let ablob = r.o;
    // hlx:388
    take(&mut r, ablob_len)?;
    // hlx:389
    let aloff = r.o;
    // hlx:390
    take(&mut r, n.checked_add(1)?.checked_mul(4)?)?;
    // hlx:391
    let atotal = word(&buf, aloff + n * 4);
    // hlx:392
    let aids = r.o;
    // hlx:393
    take(&mut r, atotal.checked_mul(4)?)?;
    // hlx:394
    if r.o != end {
        // hlx:395
        return None;
        // hlx:396
    }
    // hlx:397
    for i in 0..vn {
        // hlx:398
        if word(&buf, voff + i * 4) > word(&buf, voff + i * 4 + 4)
            || word(&buf, voff + i * 4 + 4) > blob
            || word(&buf, poff + i * 4) > word(&buf, poff + i * 4 + 4)
            || word(&buf, poff + i * 4 + 4) > total
        {
            // hlx:399
            return None;
            // hlx:400
        }
        // hlx:401
    }
    // hlx:402
    for i in 0..total {
        // hlx:403
        if word(&buf, pdoc + i * 4) >= n {
            // hlx:404
            return None;
            // hlx:405
        }
        // hlx:406
    }
    // hlx:407
    for i in 0..avn {
        // hlx:408
        if word(&buf, aoff + i * 4) > word(&buf, aoff + i * 4 + 4)
            || word(&buf, aoff + i * 4 + 4) > ablob_len
        {
            // hlx:409
            return None;
            // hlx:410
        }
        // hlx:411
    }
    // hlx:412
    for i in 0..n {
        // hlx:413
        if word(&buf, aloff + i * 4) > word(&buf, aloff + i * 4 + 4)
            || word(&buf, aloff + i * 4 + 4) > atotal
        {
            // hlx:414
            return None;
            // hlx:415
        }
        // hlx:416
    }
    // hlx:417
    for i in 0..atotal {
        // hlx:418
        if word(&buf, aids + i * 4) >= avn {
            // hlx:419
            return None;
            // hlx:420
        }
        // hlx:421
    }
    // hlx:422
    Some((
        all,
        pos,
        Index {
            buf,
            lens,
            vn,
            voff,
            vblob,
            poff,
            pdoc,
            ptf,
            avn,
            aoff,
            ablob,
            aloff,
            aids,
        },
    ))
    // hlx:423
}
// hlx:427
pub(super) fn scores(ix: &Index, pos: &[u32], count: usize, query: &str) -> Vec<f32> {
    // hlx:428
    let mut terms = super::tokens(query);
    // hlx:429
    terms.sort();
    // hlx:430
    terms.dedup();
    // hlx:431
    if terms.is_empty() || count == 0 {
        // hlx:432
        return vec![0.0; count];
        // hlx:433
    }
    // hlx:434
    let b = &ix.buf;
    // hlx:435
    let mut total_length = 0usize;
    // hlx:436
    for i in 0..pos.len() {
        // hlx:437
        if pos[i] != u32::MAX {
            // hlx:438
            total_length += word(b, ix.lens + i * 4);
            // hlx:439
        }
        // hlx:440
    }
    // hlx:441
    let n = count as f32;
    // hlx:442
    let avgdl = (total_length as f32 / n).max(1.0);
    // hlx:443
    let mut out = vec![0.0f32; count];
    // hlx:444
    for term in &terms {
        // hlx:445
        let (mut lo, mut hi) = (0usize, ix.vn);
        // hlx:446
        for _ in 0..40 {
            // hlx:447
            if lo >= hi {
                // hlx:448
                break;
                // hlx:449
            }
            // hlx:450
            let mid = (lo + hi) / 2;
            // hlx:451
            let word_at = &b
                [ix.vblob + word(b, ix.voff + mid * 4)..ix.vblob + word(b, ix.voff + mid * 4 + 4)];
            // hlx:452
            if word_at < term.as_bytes() {
                // hlx:453
                lo = mid + 1;
                // hlx:454
            } else {
                // hlx:455
                hi = mid;
                // hlx:456
            }
            // hlx:457
        }
        // hlx:458
        if lo >= ix.vn
            || &b[ix.vblob + word(b, ix.voff + lo * 4)..ix.vblob + word(b, ix.voff + lo * 4 + 4)]
                != term.as_bytes()
        {
            // hlx:459
            continue;
            // hlx:460
        }
        // hlx:461
        let (from, to) = (word(b, ix.poff + lo * 4), word(b, ix.poff + lo * 4 + 4));
        // hlx:462
        let df = (from..to)
            .filter(|&j| pos[word(b, ix.pdoc + j * 4)] != u32::MAX)
            .count() as f32;
        // hlx:463
        let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
        // hlx:464
        for j in from..to {
            // hlx:465
            let doc = word(b, ix.pdoc + j * 4);
            // hlx:466
            if pos[doc] != u32::MAX {
                // hlx:467
                let tf = word(b, ix.ptf + j * 4) as f32;
                // hlx:468
                let length = word(b, ix.lens + doc * 4) as f32;
                // hlx:469
                out[pos[doc] as usize] +=
                    idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / avgdl));
                // hlx:470
            }
            // hlx:471
        }
        // hlx:472
    }
    // hlx:473
    out
    // hlx:474
}
// hlx:477
pub(super) fn common_anchors(
    ix: &Index,
    pos: &[u32],
    count: usize,
) -> std::collections::HashSet<String> {
    // hlx:478
    let b = &ix.buf;
    // hlx:479
    let mut df = vec![0usize; ix.avn];
    // hlx:480
    for doc in 0..pos.len() {
        // hlx:481
        if pos[doc] != u32::MAX {
            // hlx:482
            for j in word(b, ix.aloff + doc * 4)..word(b, ix.aloff + doc * 4 + 4) {
                // hlx:483
                df[word(b, ix.aids + j * 4)] += 1;
                // hlx:484
            }
            // hlx:485
        }
        // hlx:486
    }
    // hlx:487
    let mut out = std::collections::HashSet::new();
    // hlx:488
    for (i, c) in df.iter().enumerate() {
        // hlx:489
        if c * 10 > count {
            // hlx:490
            out.insert(
                String::from_utf8_lossy(
                    &b[ix.ablob + word(b, ix.aoff + i * 4)
                        ..ix.ablob + word(b, ix.aoff + i * 4 + 4)],
                )
                .into_owned(),
            );
            // hlx:491
        }
        // hlx:492
    }
    // hlx:493
    out
    // hlx:494
}
// hlx:497
#[test]
// hlx:498
fn legacy_snapshot_with_a_valid_checksum_is_rejected() {
    // hlx:499
    let key = Key {
        len: 0,
        a: 10,
        b: 20,
        weights: [1, 2, 1, 1],
    };
    // hlx:500
    let current = encode(&key, &[]);
    // hlx:501
    let n = check(&current, &key).expect("current snapshot is valid");
    // hlx:502
    let mut previous = current[..n].to_vec();
    // hlx:503
    previous[..8].copy_from_slice(b"INSTIDX2");
    // hlx:504
    let (a, b) = mix(&previous);
    // hlx:505
    put_u64(&mut previous, a);
    // hlx:506
    put_u64(&mut previous, b);
    // hlx:507
    assert_eq!(check(&previous, &key), None);
    // hlx:508
}