-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathtests.zig
More file actions
7164 lines (5976 loc) · 273 KB
/
tests.zig
File metadata and controls
7164 lines (5976 loc) · 273 KB
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
const std = @import("std");
const cio = @import("cio.zig");
const testing = std.testing;
const io = std.testing.io;
const Store = @import("store.zig").Store;
const ChangeEntry = @import("store.zig").ChangeEntry;
const AgentRegistry = @import("agent.zig").AgentRegistry;
const Explorer = @import("explore.zig").Explorer;
const SearchResult = @import("explore.zig").SearchResult;
const WordIndex = @import("index.zig").WordIndex;
const TrigramIndex = @import("index.zig").TrigramIndex;
const SparseNgramIndex = @import("index.zig").SparseNgramIndex;
const pairWeight = @import("index.zig").pairWeight;
const extractSparseNgrams = @import("index.zig").extractSparseNgrams;
const buildCoveringSet = @import("index.zig").buildCoveringSet;
const setFrequencyTable = @import("index.zig").setFrequencyTable;
const resetFrequencyTable = @import("index.zig").resetFrequencyTable;
const buildFrequencyTable = @import("index.zig").buildFrequencyTable;
const writeFrequencyTable = @import("index.zig").writeFrequencyTable;
const readFrequencyTable = @import("index.zig").readFrequencyTable;
const WordTokenizer = @import("index.zig").WordTokenizer;
const splitIdentifier = @import("index.zig").splitIdentifier;
const version = @import("version.zig");
const watcher = @import("watcher.zig");
const edit_mod = @import("edit.zig");
const snapshot_json = @import("snapshot_json.zig");
const explore = @import("explore.zig");
const extractLines = explore.extractLines;
const isCommentOrBlank = explore.isCommentOrBlank;
const Language = explore.Language;
const SymbolKind = explore.SymbolKind;
const DependencyGraph = explore.DependencyGraph;
const SymbolLocation = explore.SymbolLocation;
const mcp_mod = @import("mcp.zig");
const main_mod = @import("main.zig");
const nuke_mod = @import("nuke.zig");
const update_mod = @import("update.zig");
const snapshot_mod = @import("snapshot.zig");
const telemetry_mod = @import("telemetry.zig");
// ── Store tests ─────────────────────────────────────────────
test "store: record and retrieve snapshots" {
var store = Store.init(testing.allocator);
defer store.deinit();
const seq1 = try store.recordSnapshot("foo.zig", 100, 0xABC);
const seq2 = try store.recordSnapshot("bar.zig", 200, 0xDEF);
try testing.expect(seq1 == 1);
try testing.expect(seq2 == 2);
try testing.expect(store.currentSeq() == 2);
}
test "store: getLatest returns most recent version" {
var store = Store.init(testing.allocator);
defer store.deinit();
_ = try store.recordSnapshot("foo.zig", 100, 0x111);
_ = try store.recordSnapshot("foo.zig", 200, 0x222);
const latest = store.getLatest("foo.zig").?;
try testing.expect(latest.seq == 2);
try testing.expect(latest.size == 200);
try testing.expect(latest.hash == 0x222);
}
test "store: getLatest returns null for unknown file" {
var store = Store.init(testing.allocator);
defer store.deinit();
try testing.expect(store.getLatest("nope.zig") == null);
}
test "store: changesSince counts correctly" {
var store = Store.init(testing.allocator);
defer store.deinit();
_ = try store.recordSnapshot("a.zig", 10, 0);
_ = try store.recordSnapshot("b.zig", 20, 0);
_ = try store.recordSnapshot("c.zig", 30, 0);
try testing.expect(store.changesSince(0) == 3);
try testing.expect(store.changesSince(1) == 2);
try testing.expect(store.changesSince(3) == 0);
}
test "store: changesSinceDetailed" {
var store = Store.init(testing.allocator);
defer store.deinit();
_ = try store.recordSnapshot("a.zig", 10, 0);
_ = try store.recordSnapshot("b.zig", 20, 0);
_ = try store.recordSnapshot("a.zig", 15, 0);
const changes = try store.changesSinceDetailed(1, testing.allocator);
defer testing.allocator.free(changes);
try testing.expect(changes.len == 2); // a.zig and b.zig both changed
}
test "store: recordDelete creates tombstone" {
var store = Store.init(testing.allocator);
defer store.deinit();
_ = try store.recordSnapshot("del.zig", 50, 0);
_ = try store.recordDelete("del.zig", 0);
const latest = store.getLatest("del.zig").?;
try testing.expect(latest.op == .tombstone);
try testing.expect(latest.size == 0);
}
test "store: getAtCursor" {
var store = Store.init(testing.allocator);
defer store.deinit();
_ = try store.recordSnapshot("f.zig", 10, 0x10);
_ = try store.recordSnapshot("f.zig", 20, 0x20);
_ = try store.recordSnapshot("f.zig", 30, 0x30);
const at1 = store.getAtCursor("f.zig", 1).?;
try testing.expect(at1.size == 10);
const at2 = store.getAtCursor("f.zig", 2).?;
try testing.expect(at2.size == 20);
const at3 = store.getAtCursor("f.zig", 99).?;
try testing.expect(at3.size == 30);
}
test "store: recordEdit persists diff data to data log" {
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const dir_path_len = try tmp_dir.dir.realPathFile(io, ".", &dir_buf);
const dir_path = dir_buf[0..dir_path_len];
const log_path = try std.fmt.allocPrint(testing.allocator, "{s}/data.log", .{dir_path});
defer testing.allocator.free(log_path);
var store = Store.init(testing.allocator);
defer store.deinit();
try store.openDataLog(io, log_path);
const diff = "replace body";
_ = try store.recordEdit("foo.zig", 1, .replace, 0x1234, diff.len, diff);
const latest = store.getLatest("foo.zig").?;
try testing.expectEqual(@as(?u64, 0), latest.data_offset);
try testing.expectEqual(@as(u32, diff.len), latest.data_len);
const log_file = try std.Io.Dir.cwd().openFile(io, log_path, .{});
defer log_file.close(io);
var buf: [32]u8 = undefined;
const read_len = try log_file.readPositionalAll(io, buf[0..diff.len], 0);
try testing.expectEqual(diff.len, read_len);
try testing.expectEqualStrings(diff, buf[0..diff.len]);
}
// ── Agent tests ─────────────────────────────────────────────
test "agent: register and heartbeat" {
var agents = AgentRegistry.init(testing.allocator);
defer agents.deinit();
const id = try agents.register("test-agent");
try testing.expect(id == 1);
agents.heartbeat(id);
// No crash = success
}
test "agent: register multiple agents" {
var agents = AgentRegistry.init(testing.allocator);
defer agents.deinit();
const a = try agents.register("alpha");
const b = try agents.register("beta");
try testing.expect(a == 1);
try testing.expect(b == 2);
}
test "agent: lock and unlock" {
var agents = AgentRegistry.init(testing.allocator);
defer agents.deinit();
const id = try agents.register("locker");
const got = try agents.tryLock(id, "file.zig", 60_000);
try testing.expect(got == true);
agents.releaseLock(id, "file.zig");
}
test "agent: lock contention between agents" {
var agents = AgentRegistry.init(testing.allocator);
defer agents.deinit();
const a = try agents.register("agent-a");
const b = try agents.register("agent-b");
// A locks the file
const got_a = try agents.tryLock(a, "shared.zig", 60_000);
try testing.expect(got_a == true);
// B should be denied
const got_b = try agents.tryLock(b, "shared.zig", 60_000);
try testing.expect(got_b == false);
// A releases
agents.releaseLock(a, "shared.zig");
// B can now lock
const got_b2 = try agents.tryLock(b, "shared.zig", 60_000);
try testing.expect(got_b2 == true);
}
test "agent: same-agent relock does not duplicate lock key" {
var agents = AgentRegistry.init(testing.allocator);
defer agents.deinit();
const id = try agents.register("agent-relock");
try testing.expect(try agents.tryLock(id, "shared.zig", 60_000));
try testing.expect(try agents.tryLock(id, "shared.zig", 60_000));
const agent = agents.agents.getPtr(id) orelse return error.TestUnexpectedResult;
try testing.expect(agent.locked_paths.count() == 1);
agents.releaseLock(id, "shared.zig");
try testing.expect(agent.locked_paths.count() == 0);
}
test "agent: reapStale frees lock keys and clears map" {
var agents = AgentRegistry.init(testing.allocator);
defer agents.deinit();
const id = try agents.register("agent-stale");
try testing.expect(try agents.tryLock(id, "a.zig", 60_000));
try testing.expect(try agents.tryLock(id, "b.zig", 60_000));
const agent = agents.agents.getPtr(id) orelse return error.TestUnexpectedResult;
agent.last_seen = 0;
agents.reapStale(0);
try testing.expect(agent.state == .crashed);
try testing.expect(agent.locked_paths.count() == 0);
}
// ── Word index tests ────────────────────────────────────────
test "word tokenizer" {
var tok = WordTokenizer{ .buf = "pub fn main() !void {" };
const w1 = tok.next().?;
try testing.expectEqualStrings("pub", w1);
const w2 = tok.next().?;
try testing.expectEqualStrings("fn", w2);
const w3 = tok.next().?;
try testing.expectEqualStrings("main", w3);
const w4 = tok.next().?;
try testing.expectEqualStrings("void", w4);
try testing.expect(tok.next() == null);
}
test "word index: index and search" {
var wi = WordIndex.init(testing.allocator);
defer wi.deinit();
try wi.indexFile("src/foo.zig", "pub fn hello() void {\n const x = 42;\n}\n");
const hits = wi.search("hello");
try testing.expect(hits.len > 0);
try testing.expectEqualStrings("src/foo.zig", wi.hitPath(hits[0]));
try testing.expect(hits[0].line_num == 1);
// "x" is only 1 char, should be skipped
const x_hits = wi.search("x");
try testing.expect(x_hits.len == 0);
// "const" should be found
const const_hits = wi.search("const");
try testing.expect(const_hits.len > 0);
try testing.expect(const_hits[0].line_num == 2);
}
test "word index: re-index clears old entries" {
var wi = WordIndex.init(testing.allocator);
defer wi.deinit();
try wi.indexFile("f.zig", "fn old_func() void {}");
try testing.expect(wi.search("old_func").len > 0);
try wi.indexFile("f.zig", "fn new_func() void {}");
try testing.expect(wi.search("old_func").len == 0);
try testing.expect(wi.search("new_func").len > 0);
}
test "word index: removeFile" {
var wi = WordIndex.init(testing.allocator);
defer wi.deinit();
try wi.indexFile("a.zig", "fn hello() void {}");
try testing.expect(wi.search("hello").len > 0);
wi.removeFile("a.zig");
try testing.expect(wi.search("hello").len == 0);
}
test "word index: deduped search" {
var wi = WordIndex.init(testing.allocator);
defer wi.deinit();
// "hello" appears twice on the same line — should dedup
try wi.indexFile("f.zig", "hello hello world");
const hits = try wi.searchDeduped("hello", testing.allocator);
defer testing.allocator.free(hits);
try testing.expect(hits.len == 1);
}
// ── Trigram index tests ─────────────────────────────────────
test "trigram index: index and candidate lookup" {
var ti = TrigramIndex.init(testing.allocator);
defer ti.deinit();
try ti.indexFile("src/store.zig", "pub fn recordSnapshot(self: *Store) void {}");
try ti.indexFile("src/agent.zig", "pub fn register(self: *Agent) void {}");
const cands = ti.candidates("recordSnapshot", testing.allocator);
defer if (cands) |c| testing.allocator.free(c);
try testing.expect(cands != null);
try testing.expect(cands.?.len == 1);
try testing.expectEqualStrings("src/store.zig", cands.?[0]);
}
test "trigram index: short query returns null" {
var ti = TrigramIndex.init(testing.allocator);
defer ti.deinit();
try ti.indexFile("f.zig", "hello world");
const cands = ti.candidates("hi", testing.allocator);
try testing.expect(cands == null);
}
test "trigram index: no match returns empty" {
var ti = TrigramIndex.init(testing.allocator);
defer ti.deinit();
try ti.indexFile("f.zig", "hello world");
const cands = ti.candidates("zzzzz", testing.allocator);
try testing.expect(cands != null);
try testing.expect(cands.?.len == 0);
}
test "trigram index: re-index removes old trigrams" {
var ti = TrigramIndex.init(testing.allocator);
defer ti.deinit();
try ti.indexFile("f.zig", "uniqueOldContent");
const c1 = ti.candidates("uniqueOld", testing.allocator);
defer if (c1) |c| testing.allocator.free(c);
try testing.expect(c1 != null and c1.?.len == 1);
try ti.indexFile("f.zig", "brandNewStuff");
const c2 = ti.candidates("uniqueOld", testing.allocator);
defer if (c2) |c| testing.allocator.free(c);
try testing.expect(c2 != null and c2.?.len == 0);
const c3 = ti.candidates("brandNew", testing.allocator);
defer if (c3) |c| testing.allocator.free(c);
try testing.expect(c3 != null and c3.?.len == 1);
}
// ── Sparse N-gram tests ─────────────────────────────────────
test "pairWeight: deterministic" {
const w1 = pairWeight('a', 'b');
const w2 = pairWeight('a', 'b');
try testing.expectEqual(w1, w2);
const w3 = pairWeight('a', 'c');
// Different pair must (almost certainly) produce a different weight.
// We only assert they're not trivially equal; hash collisions are acceptable.
_ = w3; // just ensure it compiles and doesn't crash
}
test "pairWeight: different pairs produce different values (sanity)" {
// 'ab' and 'ba' should almost never collide for a reasonable hash.
const w_ab = pairWeight('a', 'b');
const w_ba = pairWeight('b', 'a');
// Not a strict requirement (collisions are ok), but verify the function runs.
_ = w_ab;
_ = w_ba;
}
test "extractSparseNgrams: short content returns empty" {
const ng = try extractSparseNgrams("ab", testing.allocator);
defer testing.allocator.free(ng);
try testing.expectEqual(@as(usize, 0), ng.len);
}
test "extractSparseNgrams: minimum length content yields one ngram" {
const ng = try extractSparseNgrams("abc", testing.allocator);
defer testing.allocator.free(ng);
try testing.expect(ng.len >= 1);
try testing.expectEqual(@as(usize, 3), ng[0].len);
try testing.expectEqual(@as(usize, 0), ng[0].pos);
}
test "extractSparseNgrams: deterministic across calls" {
const ng1 = try extractSparseNgrams("hello world", testing.allocator);
defer testing.allocator.free(ng1);
const ng2 = try extractSparseNgrams("hello world", testing.allocator);
defer testing.allocator.free(ng2);
try testing.expectEqual(ng1.len, ng2.len);
for (ng1, ng2) |a, b| {
try testing.expectEqual(a.hash, b.hash);
try testing.expectEqual(a.pos, b.pos);
try testing.expectEqual(a.len, b.len);
}
}
test "extractSparseNgrams: case-insensitive hashing" {
const ng_lower = try extractSparseNgrams("hello", testing.allocator);
defer testing.allocator.free(ng_lower);
const ng_upper = try extractSparseNgrams("HELLO", testing.allocator);
defer testing.allocator.free(ng_upper);
try testing.expectEqual(ng_lower.len, ng_upper.len);
for (ng_lower, ng_upper) |lo, hi| {
try testing.expectEqual(lo.hash, hi.hash);
}
}
test "extractSparseNgrams: ngrams cover entire content" {
const content = "the quick brown fox";
const ng = try extractSparseNgrams(content, testing.allocator);
defer testing.allocator.free(ng);
// Verify every byte position is covered by at least one n-gram.
var covered = try testing.allocator.alloc(bool, content.len);
defer testing.allocator.free(covered);
@memset(covered, false);
for (ng) |n| {
for (n.pos..n.pos + n.len) |p| {
covered[p] = true;
}
}
for (covered) |c| {
try testing.expect(c);
}
}
test "extractSparseNgrams: coverage with force-split remainder 1 (len=17)" {
// 17 identical chars → no interior local maxima → one span of length 17.
// Force-split: one MAX_NGRAM_LEN=16 chunk, remainder=1 → must still cover byte 16.
const content = "aaaaaaaaaaaaaaaaa"; // 17 'a's
const ng = try extractSparseNgrams(content, testing.allocator);
defer testing.allocator.free(ng);
var covered = try testing.allocator.alloc(bool, content.len);
defer testing.allocator.free(covered);
@memset(covered, false);
for (ng) |n| {
for (n.pos..n.pos + n.len) |p| covered[p] = true;
}
for (covered) |c| try testing.expect(c);
}
test "extractSparseNgrams: coverage with force-split remainder 2 (len=18)" {
// 18 identical chars → remainder=2 → must still cover bytes 16-17.
const content = "aaaaaaaaaaaaaaaaaa"; // 18 'a's
const ng = try extractSparseNgrams(content, testing.allocator);
defer testing.allocator.free(ng);
var covered = try testing.allocator.alloc(bool, content.len);
defer testing.allocator.free(covered);
@memset(covered, false);
for (ng) |n| {
for (n.pos..n.pos + n.len) |p| covered[p] = true;
}
for (covered) |c| try testing.expect(c);
}
test "extractSparseNgrams: ngram length bounds" {
const content = "abcdefghijklmnopqrstuvwxyz0123456789";
const ng = try extractSparseNgrams(content, testing.allocator);
defer testing.allocator.free(ng);
for (ng) |n| {
try testing.expect(n.len >= 3);
try testing.expect(n.len <= 16);
}
}
test "buildCoveringSet: sliding window covers all query substrings" {
// "foobar" (6 chars); lengths [3,6] yield 4+3+2+1 = 10 substrings.
const ngrams = try buildCoveringSet("foobar", testing.allocator);
defer testing.allocator.free(ngrams);
try testing.expectEqual(@as(usize, 10), ngrams.len);
for (ngrams) |ng| try testing.expect(ng.len >= 3 and ng.len <= 6);
}
test "buildCoveringSet: short query returns empty" {
const ngrams = try buildCoveringSet("ab", testing.allocator);
defer testing.allocator.free(ngrams);
try testing.expectEqual(@as(usize, 0), ngrams.len);
}
test "sparse ngram index: index and candidate lookup" {
var sni = SparseNgramIndex.init(testing.allocator);
defer sni.deinit();
// Index each file with content equal to the query we'll use — this
// guarantees the sparse n-gram boundaries align (same string = same weights).
const foo_query = "recordSnapshot";
const bar_query = "registerAgent";
try sni.indexFile("src/foo.zig", foo_query);
try sni.indexFile("src/bar.zig", bar_query);
const cands = sni.candidates(foo_query, testing.allocator);
defer if (cands) |c| testing.allocator.free(c);
try testing.expect(cands != null);
var found_foo = false;
var found_bar = false;
if (cands) |cs| {
for (cs) |p| {
if (std.mem.eql(u8, p, "src/foo.zig")) found_foo = true;
if (std.mem.eql(u8, p, "src/bar.zig")) found_bar = true;
}
}
try testing.expect(found_foo);
try testing.expect(!found_bar);
}
test "sparse ngram index: short query returns null" {
var sni = SparseNgramIndex.init(testing.allocator);
defer sni.deinit();
try sni.indexFile("f.zig", "hello world");
const cands = sni.candidates("hi", testing.allocator); // length 2 < MIN_LEN
try testing.expect(cands == null);
}
test "sparse ngram index: re-index removes old ngrams" {
var sni = SparseNgramIndex.init(testing.allocator);
defer sni.deinit();
try sni.indexFile("f.zig", "uniqueOldContent");
const c1 = sni.candidates("uniqueOldContent", testing.allocator);
defer if (c1) |c| testing.allocator.free(c);
try testing.expect(c1 != null and c1.?.len == 1);
try sni.indexFile("f.zig", "brandNewStuff");
const c2 = sni.candidates("uniqueOldContent", testing.allocator);
defer if (c2) |c| testing.allocator.free(c);
// After re-index the old content is gone; may return empty or null.
if (c2) |cs| try testing.expectEqual(@as(usize, 0), cs.len);
}
test "sparse ngram index: removeFile prunes entries" {
var sni = SparseNgramIndex.init(testing.allocator);
defer sni.deinit();
try sni.indexFile("a.zig", "hello world foo bar");
try testing.expectEqual(@as(u32, 1), sni.fileCount());
sni.removeFile("a.zig");
try testing.expectEqual(@as(u32, 0), sni.fileCount());
}
test "sparse ngram candidates: sliding window finds file with short n-gram" {
var sni = SparseNgramIndex.init(testing.allocator);
defer sni.deinit();
// "a.zig" is indexed with content "rec" — produces the 3-char n-gram "rec".
// "b.zig" is indexed with unrelated content.
try sni.indexFile("a.zig", "rec");
try sni.indexFile("b.zig", "xxxxxxxxxx");
// Query "record" (6 chars) contains "rec" as a 3-char sliding-window
// substring. buildCoveringSet generates "rec" → hash matches the indexed
// n-gram of "a.zig".
const cands = sni.candidates("record", testing.allocator);
defer if (cands) |c| testing.allocator.free(c);
var found_a = false;
if (cands) |cs| {
for (cs) |p| if (std.mem.eql(u8, p, "a.zig")) {
found_a = true;
};
}
try testing.expect(found_a);
}
test "explorer: sparse ngram index integrated into searchContent" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("src/alpha.zig", "pub fn processRequest(req: *Request) void {}");
try explorer.indexFile("src/beta.zig", "pub fn handleResponse(res: *Response) void {}");
const results = try explorer.searchContent("processRequest", arena.allocator(), 10);
try testing.expectEqual(@as(usize, 1), results.len);
try testing.expectEqualStrings("src/alpha.zig", results[0].path);
}
test "explorer: searchContent finds query embedded in longer identifier" {
// Verify that searchContent correctly finds files whose content contains
// the query string. The sparse index (sliding-window) and trigram index
// are both used; the intersection narrows results without false negatives.
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
// "alpha.zig" content contains "record"; "beta.zig" does not.
try explorer.indexFile("alpha.zig", "const record_count: usize = 0;");
try explorer.indexFile("beta.zig", "const unrelated_data: usize = 0;");
const results = try explorer.searchContent("record", arena.allocator(), 10);
var found = false;
for (results) |r| if (std.mem.eql(u8, r.path, "alpha.zig")) {
found = true;
};
try testing.expect(found);
}
// ── Frequency-weighted pairWeight tests ─────────────────────
test "pairWeight: common pairs have lower weight than rare pairs" {
// Common English/code pairs should have lower base weight than rare pairs.
// 'th' and 'er' are in the default_pair_freq table with weight 0x1000.
// 'qx' and 'zj' are not in the table and default to 0xFE00.
// jitter adds 0-255, so common+max_jitter (0x10FF) < rare+min_jitter (0xFE00).
const w_th = pairWeight('t', 'h');
const w_er = pairWeight('e', 'r');
const w_qx = pairWeight('q', 'x');
const w_zj = pairWeight('z', 'j');
try testing.expect(w_th < w_qx);
try testing.expect(w_er < w_zj);
}
test "pairWeight: frequency-weighted produces fewer boundaries for common text" {
// A string composed of very common pairs should produce few local maxima
// (interior weights are low and similar), giving fewer n-grams than a
// string of rare pairs.
const common = "thehereinandonthere";
const rare = "qxzjvkqxzjvkqxzjvk";
const ng_common = try extractSparseNgrams(common, testing.allocator);
defer testing.allocator.free(ng_common);
const ng_rare = try extractSparseNgrams(rare, testing.allocator);
defer testing.allocator.free(ng_rare);
// Rare pairs create more local maxima → more (shorter) n-grams.
try testing.expect(ng_rare.len >= ng_common.len);
}
test "pairWeight: deterministic with frequency table" {
const w1 = pairWeight('a', 'b');
const w2 = pairWeight('a', 'b');
try testing.expectEqual(w1, w2);
// Verify common and rare pairs also remain deterministic.
try testing.expectEqual(pairWeight('t', 'h'), pairWeight('t', 'h'));
try testing.expectEqual(pairWeight('q', 'x'), pairWeight('q', 'x'));
}
test "buildFrequencyTable: common pairs get lower weight than absent pairs" {
// Construct content where 'ab' appears many times and 'qx' never appears.
const content = "ababababababababababab";
const table = buildFrequencyTable(content);
// 'ab' is frequent → low weight; 'qx' absent → default high (0xFE00).
try testing.expect(table['a']['b'] < table['q']['x']);
try testing.expectEqual(@as(u16, 0xFE00), table['q']['x']);
}
test "frequency table: disk round-trip" {
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const dir_path_len = try tmp_dir.dir.realPathFile(io, ".", &dir_buf);
const dir_path = dir_buf[0..dir_path_len];
// Build a table with distinct values.
const content = "ababcdcdefefghghijij";
const original = buildFrequencyTable(content);
try writeFrequencyTable(io, &original, dir_path);
const loaded_opt = try readFrequencyTable(io, dir_path, testing.allocator);
try testing.expect(loaded_opt != null);
const loaded = loaded_opt.?;
defer testing.allocator.destroy(loaded);
// Byte-for-byte identical.
try testing.expectEqualSlices(
u16,
@as([*]const u16, @ptrCast(&original))[0 .. 256 * 256],
@as([*]const u16, @ptrCast(loaded))[0 .. 256 * 256],
);
}
test "frequency table: little-endian byte order on disk" {
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const dir_path_len = try tmp_dir.dir.realPathFile(io, ".", &dir_buf);
const dir_path = dir_buf[0..dir_path_len];
var table: [256][256]u16 = .{.{0} ** 256} ** 256;
table[0][0] = 0x1234; // little-endian on disk: 0x34, 0x12
table[0][1] = 0xABCD; // little-endian on disk: 0xCD, 0xAB
try writeFrequencyTable(io, &table, dir_path);
const file_path = try std.fmt.allocPrint(testing.allocator, "{s}/pair_freq.bin", .{dir_path});
defer testing.allocator.free(file_path);
const f = try std.Io.Dir.cwd().openFile(io, file_path, .{});
defer f.close(io);
var raw: [4]u8 = undefined;
try testing.expectEqual(@as(usize, 4), try f.readPositionalAll(io, &raw, 0));
try testing.expectEqual(@as(u8, 0x34), raw[0]);
try testing.expectEqual(@as(u8, 0x12), raw[1]);
try testing.expectEqual(@as(u8, 0xCD), raw[2]);
try testing.expectEqual(@as(u8, 0xAB), raw[3]);
const loaded = try readFrequencyTable(io, dir_path, testing.allocator);
try testing.expect(loaded != null);
defer testing.allocator.destroy(loaded.?);
try testing.expectEqual(@as(u16, 0x1234), loaded.?[0][0]);
try testing.expectEqual(@as(u16, 0xABCD), loaded.?[0][1]);
}
test "setFrequencyTable / resetFrequencyTable: pairWeight output changes" {
// Build a table where 'th' is rare (high weight) — opposite of default.
var custom: [256][256]u16 = .{.{0x1000} ** 256} ** 256; // all common
custom['q']['x'] = 0xFE00; // make 'qx' rare
const before_th = pairWeight('t', 'h');
const before_qx = pairWeight('q', 'x');
setFrequencyTable(&custom);
defer resetFrequencyTable();
const after_th = pairWeight('t', 'h');
const after_qx = pairWeight('q', 'x');
// After swap: 'th' should be lower (we set it to 0x1000 vs default table's 0x1000 — same).
// What definitely changes: 'qx' base shifts from 0xFE00 to 0xFE00 (custom kept it high).
// More importantly verify that resetting restores original values.
resetFrequencyTable();
try testing.expectEqual(before_th, pairWeight('t', 'h'));
try testing.expectEqual(before_qx, pairWeight('q', 'x'));
_ = after_th;
_ = after_qx;
}
// ── Explorer tests ──────────────────────────────────────────
test "explorer: index file and get outline" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("test.zig",
\\const std = @import("std");
\\pub fn main() !void {}
\\pub const Store = struct {};
);
var outline = (try explorer.getOutline("test.zig", testing.allocator)) orelse return error.TestUnexpectedResult;
defer outline.deinit();
try testing.expect(outline.line_count == 3);
try testing.expect(outline.symbols.items.len == 3);
}
test "explorer: findSymbol" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("a.zig", "pub fn alpha() void {}");
try explorer.indexFile("b.zig", "pub fn beta() void {}");
const result = try explorer.findSymbol("alpha", arena.allocator());
try testing.expect(result != null);
try testing.expectEqualStrings("a.zig", result.?.path);
}
test "explorer: findAllSymbols returns multiple" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("a.zig", "const Store = @import(\"store.zig\").Store;");
try explorer.indexFile("b.zig", "pub const Store = struct {};");
const results = try explorer.findAllSymbols("Store", arena.allocator());
defer arena.allocator().free(results);
try testing.expect(results.len == 2);
}
test "explorer: searchContent with trigram acceleration" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("store.zig", "pub fn recordSnapshot(self: *Store) void {}\npub fn init() void {}");
try explorer.indexFile("agent.zig", "pub fn register(self: *Agent) void {}");
const results = try explorer.searchContent("recordSnapshot", testing.allocator, 50);
defer {
for (results) |r| {
testing.allocator.free(r.path);
testing.allocator.free(r.line_text);
}
testing.allocator.free(results);
}
try testing.expect(results.len == 1);
try testing.expectEqualStrings("store.zig", results[0].path);
try testing.expect(results[0].line_num == 1);
}
test "explorer: searchWord via inverted index" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("math.zig", "pub fn add(a: i32, b: i32) i32 { return a + b; }");
const hits = try explorer.searchWord("add", testing.allocator);
defer testing.allocator.free(hits);
try testing.expect(hits.len > 0);
try testing.expectEqualStrings("math.zig", explorer.word_index.hitPath(hits[0]));
}
test "explorer: removeFile cleans up everything" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("gone.zig", "pub fn doStuff() void {}");
var before_remove = (try explorer.getOutline("gone.zig", testing.allocator)) orelse return error.TestUnexpectedResult;
before_remove.deinit();
explorer.removeFile("gone.zig");
try testing.expect((try explorer.getOutline("gone.zig", testing.allocator)) == null);
try testing.expect((try explorer.findSymbol("doStuff", testing.allocator)) == null);
}
test "explorer: python parser" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("app.py",
\\import os
\\class Server:
\\ def handle(self):
\\ pass
);
var outline = (try explorer.getOutline("app.py", testing.allocator)) orelse return error.TestUnexpectedResult;
defer outline.deinit();
try testing.expect(outline.symbols.items.len == 3); // import, class, def
}
test "explorer: typescript parser" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("index.ts",
\\import { foo } from './foo';
\\export function handleRequest() {}
\\export const PORT = 3000;
);
var outline = (try explorer.getOutline("index.ts", testing.allocator)) orelse return error.TestUnexpectedResult;
defer outline.deinit();
try testing.expect(outline.symbols.items.len >= 3);
}
test "issue-301: Dart / Flutter parser" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
var explorer = Explorer.init(arena.allocator());
try explorer.indexFile("lib/home_screen.dart",
\\import 'package:flutter/material.dart';
\\export 'src/helpers.dart';
\\part 'home_screen.g.dart';
\\
\\typedef ItemBuilder = Widget Function(BuildContext context);
\\
\\abstract class HomeScreen extends StatelessWidget {
\\ @override
\\ Widget build(BuildContext context) {
\\ return const Placeholder();
\\ }
\\}
\\
\\mixin Loader on State<StatefulWidget> {
\\ Future<void> loadData() async {}
\\}
\\
\\extension ContextX on BuildContext {
\\ ThemeData get theme => Theme.of(this);
\\}
\\
\\enum LoadState { idle, loading }
\\
\\const String appTitle = 'codedb';
);
var outline = (try explorer.getOutline("lib/home_screen.dart", testing.allocator)) orelse return error.TestUnexpectedResult;
defer outline.deinit();
try testing.expectEqual(Language.dart, outline.language);
try testing.expectEqual(@as(usize, 3), outline.imports.items.len);
var found_typedef = false;
var found_class = false;
var found_mixin = false;
var found_extension = false;
var found_enum = false;
var found_build = false;
var found_load = false;
var found_const = false;
for (outline.symbols.items) |sym| {
if (sym.kind == .type_alias and std.mem.eql(u8, sym.name, "ItemBuilder")) found_typedef = true;
if (sym.kind == .class_def and std.mem.eql(u8, sym.name, "HomeScreen")) found_class = true;
if (sym.kind == .trait_def and std.mem.eql(u8, sym.name, "Loader")) found_mixin = true;
if (sym.kind == .impl_block and std.mem.eql(u8, sym.name, "ContextX")) found_extension = true;
if (sym.kind == .enum_def and std.mem.eql(u8, sym.name, "LoadState")) found_enum = true;
if (sym.kind == .function and std.mem.eql(u8, sym.name, "build")) found_build = true;
if (sym.kind == .function and std.mem.eql(u8, sym.name, "loadData")) found_load = true;
if (sym.kind == .constant and std.mem.eql(u8, sym.name, "appTitle")) found_const = true;
}
try testing.expect(found_typedef);
try testing.expect(found_class);
try testing.expect(found_mixin);
try testing.expect(found_extension);
try testing.expect(found_enum);
try testing.expect(found_build);
try testing.expect(found_load);
try testing.expect(found_const);
const tree = try explorer.getTree(testing.allocator, false);
defer testing.allocator.free(tree);
try testing.expect(std.mem.indexOf(u8, tree, "home_screen.dart dart") != null);
}
// ── Version tests ───────────────────────────────────────────
test "file versions: append and latest" {
var fv = version.FileVersions.init(testing.allocator, "test.zig");
defer fv.deinit();
try fv.versions.append(testing.allocator, .{
.seq = 1,
.agent = 0,
.timestamp = 0,
.op = .snapshot,
.hash = 0x11,
.size = 100,
});
try fv.versions.append(testing.allocator, .{
.seq = 2,
.agent = 0,
.timestamp = 0,
.op = .replace,
.hash = 0x22,
.size = 150,
});
const latest = fv.latest().?;
try testing.expect(latest.seq == 2);
try testing.expect(latest.size == 150);
}
test "file versions: countSince" {
var fv = version.FileVersions.init(testing.allocator, "test.zig");
defer fv.deinit();
try fv.versions.append(testing.allocator, .{
.seq = 1,
.agent = 0,
.timestamp = 0,
.op = .snapshot,
.hash = 0,