-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_test.go
More file actions
executable file
·2227 lines (1926 loc) · 66.2 KB
/
Copy pathmemory_test.go
File metadata and controls
executable file
·2227 lines (1926 loc) · 66.2 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
package main
import (
"errors"
"math"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
type fakeSummarizer struct {
summarizeCalls int
labelCalls int
lastSummarizeText string
lastSummarizeMaxByte int
lastLabelText string
summarizeFn func(text string, maxBytes int) (string, error)
labelFn func(text string) (string, error)
}
func (f *fakeSummarizer) Summarize(text string, maxBytes int) (string, error) {
f.summarizeCalls++
f.lastSummarizeText = text
f.lastSummarizeMaxByte = maxBytes
if f.summarizeFn != nil {
return f.summarizeFn(text, maxBytes)
}
return text, nil
}
func (f *fakeSummarizer) Label(text string) (string, error) {
f.labelCalls++
f.lastLabelText = text
if f.labelFn != nil {
return f.labelFn(text)
}
return "label", nil
}
func mustNewMemoryStore(t *testing.T, opts MemoryStoreOptions) *MemoryStore {
t.Helper()
s, err := NewMemoryStore(opts)
if err != nil {
t.Fatalf("NewMemoryStore() error: %v", err)
}
return s
}
func TestMemoryStoreAdd_EmptyRejected(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
_, _, err := s.Add(" ", "", "", nil)
if err == nil {
t.Fatalf("expected error, got nil")
}
if got := err.Error(); got != "memory text is empty" {
t.Fatalf("unexpected error: got %q", got)
}
}
func TestMemoryStoreAdd_TrimsAssignsIDAndCreatedAt(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
start := time.Now()
c1, _, err := s.Add(" hello world ", "", "", nil)
end := time.Now()
if err != nil {
t.Fatalf("Add() error: %v", err)
}
if c1.ID != "m1" {
t.Fatalf("unexpected id: got %q", c1.ID)
}
if c1.Text != "hello world" {
t.Fatalf("unexpected stored text: got %q", c1.Text)
}
if strings.TrimSpace(c1.Label) == "" {
t.Fatalf("expected non-empty label")
}
if c1.CreatedAt.Before(start) || c1.CreatedAt.After(end) {
t.Fatalf("CreatedAt not within call window: start=%s created=%s end=%s", start, c1.CreatedAt, end)
}
c2, _, err := s.Add("second", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
if c2.ID != "m2" {
t.Fatalf("unexpected id: got %q", c2.ID)
}
}
func TestMemoryStoreAdd_SummarizeOnlyWhenTooLarge(t *testing.T) {
fs := &fakeSummarizer{
summarizeFn: func(text string, maxBytes int) (string, error) { return text, nil },
labelFn: func(text string) (string, error) { return "ok", nil },
}
s := mustNewMemoryStore(t, MemoryStoreOptions{Summarizer: fs})
if _, _, err := s.Add("small", "", "", nil); err != nil {
t.Fatalf("Add() error: %v", err)
}
if fs.summarizeCalls != 0 {
t.Fatalf("expected Summarize not to be called; got %d", fs.summarizeCalls)
}
if fs.labelCalls != 0 {
t.Fatalf("expected Label not to be called; got %d", fs.labelCalls)
}
long := strings.Repeat("x", MaxMemoryBytes+1)
if _, _, err := s.Add(long, "", "", nil); err != nil {
t.Fatalf("Add() error: %v", err)
}
if fs.summarizeCalls != 1 {
t.Fatalf("expected Summarize to be called once; got %d", fs.summarizeCalls)
}
if fs.lastSummarizeMaxByte != MaxMemoryBytes {
t.Fatalf("unexpected maxBytes passed to Summarize: got %d", fs.lastSummarizeMaxByte)
}
}
func TestMemoryStoreAdd_SummarizeWhitespaceBecomesError(t *testing.T) {
fs := &fakeSummarizer{
summarizeFn: func(text string, maxBytes int) (string, error) { return " \n\t ", nil },
labelFn: func(text string) (string, error) { return "unused", nil },
}
s := mustNewMemoryStore(t, MemoryStoreOptions{Summarizer: fs})
long := strings.Repeat("x", MaxMemoryBytes+1)
_, _, err := s.Add(long, "", "", nil)
if err == nil {
t.Fatalf("expected error, got nil")
}
if got := err.Error(); got != "summarizer returned empty memory" {
t.Fatalf("unexpected error: got %q", got)
}
}
func TestMemoryStoreAdd_SummarizeStillTooLongIsHardTruncated(t *testing.T) {
tooLong := strings.Repeat("a", MaxMemoryBytes+50)
fs := &fakeSummarizer{
summarizeFn: func(text string, maxBytes int) (string, error) { return tooLong, nil },
labelFn: func(text string) (string, error) { return "ok", nil },
}
s := mustNewMemoryStore(t, MemoryStoreOptions{Summarizer: fs})
in := strings.Repeat("x", MaxMemoryBytes+1)
c, _, err := s.Add(in, "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
if got := len([]byte(c.Text)); got > MaxMemoryBytes {
t.Fatalf("stored text exceeded MaxMemoryBytes: got %d > %d", got, MaxMemoryBytes)
}
}
func TestMemoryStoreAdd_LabelWhitespaceFallsBack(t *testing.T) {
fs := &fakeSummarizer{
labelFn: func(text string) (string, error) { return " ", nil },
}
s := mustNewMemoryStore(t, MemoryStoreOptions{Summarizer: fs})
// Fallback label uses the first 8 raw words (not stemmed), capped at 60 bytes.
c, _, err := s.Add("alpha beta gamma delta epsilon zeta eta theta iota", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
want := "alpha beta gamma delta epsilon zeta eta theta"
if c.Label != want {
t.Fatalf("unexpected fallback label: got %q want %q", c.Label, want)
}
}
func TestMemoryStoreAdd_LabelFallbackPreservesOriginalWords(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
// Words that stemming would mangle: "Running"→"run", "databases"→"databas", "Memory"→"memori".
// Fallback label should preserve the original word forms for readability.
c, _, err := s.Add("Running databases for production systems", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
want := "Running databases for production systems"
if c.Label != want {
t.Fatalf("fallback label should use original words: got %q want %q", c.Label, want)
}
}
func TestMemoryStoreAdd_SimilarityLinksAreSymmetricAndSorted(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
c1, _, err := s.Add("alpha", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
c2, _, err := s.Add("beta", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
c3, related, err := s.Add("alpha beta", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
if len(related) != 2 {
t.Fatalf("expected 2 related memories, got %d", len(related))
}
// Similarities should tie; expect deterministic fallback ordering by ID.
if related[0].ID != c1.ID || related[1].ID != c2.ID {
t.Fatalf("unexpected related ordering: got [%s, %s], want [%s, %s]", related[0].ID, related[1].ID, c1.ID, c2.ID)
}
// With BM25 doc-doc similarity, "alpha beta" is related to both "alpha" and "beta".
// Similarity should be above delta and symmetric.
const eps = 1e-12
relatedByID := make(map[string]float64)
for _, r := range related {
if r.Similarity <= s.similarityDelta {
t.Fatalf("unexpected similarity for %s: got %.15f want > %.15f", r.ID, r.Similarity, s.similarityDelta)
}
relatedByID[r.ID] = r.Similarity
}
// Verify symmetric edges on internal graph.
s.mu.RLock()
defer s.mu.RUnlock()
m1 := s.chunks[c1.ID]
m2 := s.chunks[c2.ID]
m3 := s.chunks[c3.ID]
if m1 == nil || m2 == nil || m3 == nil {
t.Fatalf("expected all chunks present")
}
want1 := relatedByID[c1.ID]
if math.Abs(m3.edges[c1.ID]-want1) > eps || math.Abs(m1.edges[c3.ID]-want1) > eps {
t.Fatalf("missing or asymmetric edge between %s and %s", c3.ID, c1.ID)
}
want2 := relatedByID[c2.ID]
if math.Abs(m3.edges[c2.ID]-want2) > eps || math.Abs(m2.edges[c3.ID]-want2) > eps {
t.Fatalf("missing or asymmetric edge between %s and %s", c3.ID, c2.ID)
}
}
func TestMemoryStoreAdd_DeltaTooHighNoEdges(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 1.1})
c1, _, err := s.Add("alpha", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
c2, related, err := s.Add("alpha", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
if len(related) != 0 {
t.Fatalf("expected no related memories, got %d", len(related))
}
s.mu.RLock()
defer s.mu.RUnlock()
if got := len(s.chunks[c1.ID].edges); got != 0 {
t.Fatalf("expected no edges on %s, got %d", c1.ID, got)
}
if got := len(s.chunks[c2.ID].edges); got != 0 {
t.Fatalf("expected no edges on %s, got %d", c2.ID, got)
}
}
func TestMemoryStoreGetByID_ReturnsNeighbors(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
a, _, err := s.Add("alpha", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
_, _, err = s.Add("beta", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
c, _, err := s.Add("alpha beta", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
got, neigh, err := s.Get(c.ID)
if err != nil {
t.Fatalf("Get() error: %v", err)
}
if got.ID != c.ID {
t.Fatalf("unexpected chunk id: got %q want %q", got.ID, c.ID)
}
if len(neigh) != 2 {
t.Fatalf("expected 2 neighbors, got %d", len(neigh))
}
// Deterministic ordering by edge similarity then ID (ties => IDs).
if neigh[0].ID != a.ID {
t.Fatalf("unexpected first neighbor: got %q want %q", neigh[0].ID, a.ID)
}
}
func TestMemoryStoreSearch_ContentOnlyNotLabel(t *testing.T) {
// Search uses content only; custom label is for display and does not affect similarity.
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
a, _, err := s.Add("alpha content", "topicA", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
_, _, err = s.Add("beta content", "topicB", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
// Query by content "alpha"; should match the chunk with content "alpha content" (id a),
// not by label "topicA".
matches, err := s.Search("alpha", "", "")
if err != nil {
t.Fatalf("Search() error: %v", err)
}
if len(matches) == 0 {
t.Fatalf("expected at least one match for content 'alpha'")
}
found := false
for _, m := range matches {
if m.Chunk.ID == a.ID {
found = true
if m.Chunk.Label != "topicA" {
t.Fatalf("chunk label should still be displayed: got %q", m.Chunk.Label)
}
break
}
}
if !found {
t.Fatalf("expected content-based match for chunk %q", a.ID)
}
}
func TestMemoryStoreSearch_LexicalMatchBypassesCosineThreshold(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.5})
// Ensure cosine similarity stays below delta due to many tokens.
text := "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda Gustav"
c, _, err := s.Add(text, "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
matches, err := s.Search("Gustav", "", "")
if err != nil {
t.Fatalf("Search() error: %v", err)
}
if len(matches) == 0 {
t.Fatalf("expected lexical match to return a result")
}
found := false
for _, m := range matches {
if m.Chunk.ID == c.ID {
found = true
break
}
}
if !found {
t.Fatalf("expected lexical match for chunk %q", c.ID)
}
}
// TestMemoryStoreSearch_BM25Used verifies that Search uses BM25: a query matching
// document content returns results with similarity above delta, and scores are deterministic.
func TestMemoryStoreSearch_BM25Used(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.2})
_, _, _ = s.Add("retrieval algorithm for search", "", "fact", nil)
_, _, _ = s.Add("database schema design", "", "fact", nil)
matches, err := s.Search("retrieval algorithm", "", "")
if err != nil {
t.Fatalf("Search() error: %v", err)
}
if len(matches) == 0 {
t.Fatal("expected at least one match for query overlapping first doc")
}
// First document should rank at or near top (BM25 or lexical match).
if matches[0].Chunk.ID != "m1" && (len(matches) < 2 || matches[1].Chunk.ID != "m1") {
// m1 is the only doc with both "retrieval" and "algorithm"; it must appear in top results
found := false
for _, m := range matches {
if m.Chunk.ID == "m1" {
found = true
break
}
}
if !found {
t.Errorf("expected m1 in results, got %v", func() []string {
ids := make([]string, len(matches))
for i, m := range matches {
ids[i] = m.Chunk.ID
}
return ids
}())
}
}
if matches[0].Similarity <= 0 {
t.Errorf("expected positive similarity, got %f", matches[0].Similarity)
}
}
func TestMemoryStoreSearch_RespectsMaxResults(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.0, MaxResults: 2})
_, _, err := s.Add("alpha beta", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
_, _, err = s.Add("alpha gamma", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
_, _, err = s.Add("alpha delta", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
matches, err := s.Search("alpha", "", "")
if err != nil {
t.Fatalf("Search() error: %v", err)
}
if got := len(matches); got != 2 {
t.Fatalf("expected 2 matches, got %d", got)
}
}
func TestMemoryStore_List_TypeFilter(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
_, _, _ = s.Add("fact one", "", "fact", nil)
_, _, _ = s.Add("story one", "", "story", nil)
_, _, _ = s.Add("fact two", "", "fact", nil)
all := s.List("", "")
if len(all) != 3 {
t.Fatalf("List() no filter: expected 3, got %d", len(all))
}
facts := s.List("fact", "")
if len(facts) != 2 {
t.Fatalf("List(\"fact\"): expected 2, got %d", len(facts))
}
for _, it := range facts {
if it.Type != "fact" {
t.Fatalf("expected type fact, got %q", it.Type)
}
}
stories := s.List("story", "")
if len(stories) != 1 {
t.Fatalf("List(\"story\"): expected 1, got %d", len(stories))
}
if stories[0].Type != "story" {
t.Fatalf("expected type story, got %q", stories[0].Type)
}
empty := s.List("nonexistent", "")
if len(empty) != 0 {
t.Fatalf("List(\"nonexistent\"): expected 0, got %d", len(empty))
}
}
func TestMemoryStore_Search_TypeFilter(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
_, _, _ = s.Add("alpha fact content", "", "fact", nil)
_, _, _ = s.Add("alpha story content", "", "story", nil)
all, err := s.Search("alpha", "", "")
if err != nil {
t.Fatal(err)
}
if len(all) != 2 {
t.Fatalf("Search no filter: expected 2 matches, got %d", len(all))
}
facts, err := s.Search("alpha", "fact", "")
if err != nil {
t.Fatal(err)
}
if len(facts) != 1 || facts[0].Chunk.Type != "fact" {
t.Fatalf("Search type=fact: expected 1 fact match, got %d", len(facts))
}
stories, err := s.Search("alpha", "story", "")
if err != nil {
t.Fatal(err)
}
if len(stories) != 1 || stories[0].Chunk.Type != "story" {
t.Fatalf("Search type=story: expected 1 story match, got %d", len(stories))
}
none, err := s.Search("alpha", "note", "")
if err != nil {
t.Fatal(err)
}
if len(none) != 0 {
t.Fatalf("Search type=note: expected 0, got %d", len(none))
}
}
func TestMemoryStore_GetContext_TypeFilter(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
_, _, _ = s.Add("#goal build the feature", "", "goal", nil)
_, _, _ = s.Add("#status in progress", "", "status", nil)
_, _, _ = s.Add("#goal another goal", "", "goal", nil)
all := s.GetContext("", "", 0)
if len(all.Memories) == 0 {
t.Fatal("GetContext() no filter: expected some memories")
}
goalOnly := s.GetContext("goal", "", 0)
countGoal := 0
for _, m := range goalOnly.Memories {
if m.Category != "#goal" {
t.Fatalf("expected category #goal, got %q", m.Category)
}
if m.Chunk.Type != "goal" {
t.Fatalf("expected type goal, got %q", m.Chunk.Type)
}
countGoal++
}
if countGoal != 2 {
t.Fatalf("GetContext(\"goal\"): expected 2, got %d", countGoal)
}
statusOnly := s.GetContext("status", "", 0)
if len(statusOnly.Memories) != 1 || statusOnly.Memories[0].Chunk.Type != "status" {
t.Fatalf("GetContext(\"status\"): expected 1 memory with type status, got %d", len(statusOnly.Memories))
}
empty := s.GetContext("nonexistent", "", 0)
if len(empty.Memories) != 0 {
t.Fatalf("GetContext(\"nonexistent\"): expected 0, got %d", len(empty.Memories))
}
}
func TestMemoryStore_GetContext_PerCategory(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
// Add 4 goals
_, _, _ = s.Add("#goal first", "", "", nil)
_, _, _ = s.Add("#goal second", "", "", nil)
_, _, _ = s.Add("#goal third", "", "", nil)
_, _, _ = s.Add("#goal fourth", "", "", nil)
// Default (0 → 2 per category)
ctx0 := s.GetContext("", "", 0)
goalCount := 0
for _, m := range ctx0.Memories {
if m.Category == "#goal" {
goalCount++
}
}
if goalCount != 2 {
t.Fatalf("default per_category: expected 2 goals, got %d", goalCount)
}
// Explicit 3 per category
ctx3 := s.GetContext("", "", 3)
goalCount = 0
for _, m := range ctx3.Memories {
if m.Category == "#goal" {
goalCount++
}
}
if goalCount != 3 {
t.Fatalf("per_category=3: expected 3 goals, got %d", goalCount)
}
// Explicit 1 per category
ctx1 := s.GetContext("", "", 1)
goalCount = 0
for _, m := range ctx1.Memories {
if m.Category == "#goal" {
goalCount++
}
}
if goalCount != 1 {
t.Fatalf("per_category=1: expected 1 goal, got %d", goalCount)
}
// Large limit (more than available) — should return all 4
ctx99 := s.GetContext("", "", 99)
goalCount = 0
for _, m := range ctx99.Memories {
if m.Category == "#goal" {
goalCount++
}
}
if goalCount != 4 {
t.Fatalf("per_category=99: expected 4 goals, got %d", goalCount)
}
}
func TestMemoryStore_GetContext_UpdatedAtSorting(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
// Add an older #status memory, then a newer one.
old, _, _ := s.Add("#status old status created first", "", "", nil)
time.Sleep(10 * time.Millisecond) // Ensure distinct timestamps
_, _, _ = s.Add("#status newer status created second", "", "", nil)
// Without updates, the newer memory should appear first (newest CreatedAt).
ctx := s.GetContext("", "", 2)
var statusTexts []string
for _, m := range ctx.Memories {
if m.Category == "#status" {
statusTexts = append(statusTexts, m.Chunk.Text)
}
}
if len(statusTexts) != 2 {
t.Fatalf("expected 2 #status memories, got %d", len(statusTexts))
}
if statusTexts[0] != "#status newer status created second" {
t.Fatalf("before update: expected newer first, got %q", statusTexts[0])
}
// Now update the older memory — its UpdatedAt becomes the most recent timestamp.
time.Sleep(10 * time.Millisecond)
s.Update(old.ID, "#status old status just updated", "", "", nil)
ctx2 := s.GetContext("", "", 2)
statusTexts = nil
for _, m := range ctx2.Memories {
if m.Category == "#status" {
statusTexts = append(statusTexts, m.Chunk.Text)
}
}
if len(statusTexts) != 2 {
t.Fatalf("expected 2 #status memories, got %d", len(statusTexts))
}
if statusTexts[0] != "#status old status just updated" {
t.Fatalf("after update: expected recently-updated first, got %q", statusTexts[0])
}
}
func TestMemoryStore_FindConsolidationPairs_Basic(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
c1, _, err := s.Add("alpha", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
c2, _, err := s.Add("alpha", "", "", nil)
if err != nil {
t.Fatalf("Add() error: %v", err)
}
// Unrelated chunk.
if _, _, err := s.Add("beta", "", "", nil); err != nil {
t.Fatalf("Add() error: %v", err)
}
pairs, err := s.FindConsolidationPairs(ConsolidationParams{MinSimilarity: 0.1})
if err != nil {
t.Fatalf("FindConsolidationPairs() error: %v", err)
}
if len(pairs) != 1 {
t.Fatalf("expected 1 pair, got %d: %+v", len(pairs), pairs)
}
p := pairs[0]
if !((p.AID == c1.ID && p.BID == c2.ID) || (p.AID == c2.ID && p.BID == c1.ID)) {
t.Fatalf("unexpected pair IDs: %+v", p)
}
if p.Similarity <= 0.1 {
t.Fatalf("expected similarity > 0.1, got %.4f", p.Similarity)
}
}
func TestMemoryStore_FindConsolidationPairs_TypeFilter(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
f1, _, _ := s.Add("alpha fact", "", "fact", nil)
f2, _, _ := s.Add("alpha fact again", "", "fact", nil)
// Same content but different type; should not appear for type=fact.
_, _, _ = s.Add("alpha fact", "", "story", nil)
pairs, err := s.FindConsolidationPairs(ConsolidationParams{
TypeFilter: "fact",
MinSimilarity: 0.1,
})
if err != nil {
t.Fatalf("FindConsolidationPairs() error: %v", err)
}
if len(pairs) != 1 {
t.Fatalf("expected 1 pair for type=fact, got %d: %+v", len(pairs), pairs)
}
p := pairs[0]
if !((p.AID == f1.ID && p.BID == f2.ID) || (p.AID == f2.ID && p.BID == f1.ID)) {
t.Fatalf("unexpected pair IDs for type filter: %+v", p)
}
if p.Type != "fact" {
t.Fatalf("expected pair Type=fact, got %q", p.Type)
}
}
func TestMemoryStore_Consolidate_BasicMergeAndDeleteSources(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
c1, _, _ := s.Add("first fact", "", "fact", nil)
c2, _, _ := s.Add("second fact", "", "fact", nil)
merged, removed, err := s.Consolidate([]string{c1.ID, c2.ID}, ConsolidateOptions{})
if err != nil {
t.Fatalf("Consolidate() error: %v", err)
}
if merged.ID == c1.ID || merged.ID == c2.ID {
t.Fatalf("expected new merged ID, got %q", merged.ID)
}
if merged.Type != "fact" {
t.Fatalf("expected merged type fact, got %q", merged.Type)
}
if !strings.Contains(merged.Text, "first fact") || !strings.Contains(merged.Text, "second fact") {
t.Fatalf("merged text does not contain both sources: %q", merged.Text)
}
if len(removed) != 2 {
t.Fatalf("expected 2 removed IDs, got %d", len(removed))
}
// Sources should no longer be retrievable.
if _, _, err := s.Get(c1.ID); err == nil {
t.Fatalf("expected error getting deleted source %s", c1.ID)
}
if _, _, err := s.Get(c2.ID); err == nil {
t.Fatalf("expected error getting deleted source %s", c2.ID)
}
}
func TestMemoryStore_Consolidate_IncompatibleTypesError(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
a, _, _ := s.Add("alpha fact", "", "fact", nil)
b, _, _ := s.Add("alpha story", "", "story", nil)
_, _, err := s.Consolidate([]string{a.ID, b.ID}, ConsolidateOptions{})
if err == nil {
t.Fatalf("expected error for incompatible types, got nil")
}
if !errors.Is(err, ErrIncompatibleTypes) {
t.Fatalf("unexpected error: %v", err)
}
}
func TestMemoryStore_Consolidate_OverrideTypeAndKeepSources(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
a, _, _ := s.Add("alpha fact", "", "fact", nil)
b, _, _ := s.Add("beta story", "", "story", nil)
del := false
merged, removed, err := s.Consolidate([]string{a.ID, b.ID}, ConsolidateOptions{
NewType: "note",
DeleteSources: &del,
})
if err != nil {
t.Fatalf("Consolidate() error: %v", err)
}
if merged.Type != "note" {
t.Fatalf("expected merged type note, got %q", merged.Type)
}
if len(removed) != 0 {
t.Fatalf("expected no removed IDs when DeleteSources=false, got %d", len(removed))
}
// Sources should still exist.
if _, _, err := s.Get(a.ID); err != nil {
t.Fatalf("expected source %s to still exist; err=%v", a.ID, err)
}
if _, _, err := s.Get(b.ID); err != nil {
t.Fatalf("expected source %s to still exist; err=%v", b.ID, err)
}
}
func TestMemoryStore_ScopeFiltering(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
// Add global memory (no scopes) with hashtag for GetContext
global, _, _ := s.Add("#status global memory", "", "", nil)
// Add project-scoped memories with hashtags
proj1, _, _ := s.Add("#status project one memory", "", "", []string{"project1"})
proj2, _, _ := s.Add("#status project two memory", "", "", []string{"project2"})
multiScope, _, _ := s.Add("#status multi-scope memory", "", "", []string{"project1", "project2"})
// Search without scope filter - should return all
all, _ := s.Search("memory", "", "")
if len(all) != 4 {
t.Fatalf("Search without scope: expected 4, got %d", len(all))
}
// Search with scope filter - should return global + matching scopes
proj1Results, _ := s.Search("memory", "", "project1")
if len(proj1Results) != 3 { // global + proj1 + multiScope
t.Fatalf("Search scope=project1: expected 3, got %d", len(proj1Results))
}
foundGlobal := false
foundProj1 := false
foundMulti := false
for _, m := range proj1Results {
if m.Chunk.ID == global.ID {
foundGlobal = true
}
if m.Chunk.ID == proj1.ID {
foundProj1 = true
}
if m.Chunk.ID == multiScope.ID {
foundMulti = true
}
}
if !foundGlobal || !foundProj1 || !foundMulti {
t.Fatalf("Search scope=project1: missing expected memories")
}
// Search with different scope
proj2Results, _ := s.Search("memory", "", "project2")
if len(proj2Results) != 3 { // global + proj2 + multiScope
t.Fatalf("Search scope=project2: expected 3, got %d", len(proj2Results))
}
// Verify proj2 is included
foundProj2 := false
for _, m := range proj2Results {
if m.Chunk.ID == proj2.ID {
foundProj2 = true
break
}
}
if !foundProj2 {
t.Fatal("Search scope=project2: proj2 memory not found")
}
// List with scope filter
proj1List := s.List("", "project1")
if len(proj1List) != 3 {
t.Fatalf("List scope=project1: expected 3, got %d", len(proj1List))
}
// GetContext with scope filter
ctx := s.GetContext("", "project1", 0)
if len(ctx.Memories) == 0 {
t.Fatal("GetContext scope=project1: expected some memories")
}
// FindRelevant with scope filter
relevant := s.FindRelevant("memory", 10, "project1", "")
if len(relevant) != 3 {
t.Fatalf("FindRelevant scope=project1: expected 3, got %d", len(relevant))
}
}
func TestMemoryStore_FindRelevant_TypeFilter(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
_, _, _ = s.Add("database choice is postgres", "", "fact", nil)
_, _, _ = s.Add("database story for the project", "", "story", nil)
results := s.FindRelevant("database", 5, "", "fact")
if len(results) != 1 {
t.Fatalf("FindRelevant type=fact: expected 1, got %d", len(results))
}
if results[0].Type != "fact" {
t.Fatalf("expected type fact, got %q", results[0].Type)
}
}
func TestMemoryStore_ScopeAwareEdgeCreation(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{SimilarityDelta: 0.1})
// Add global memory
global, _, _ := s.Add("alpha beta", "", "", nil)
// Add project1-scoped memory (similar content)
proj1, _, _ := s.Add("alpha beta gamma", "", "", []string{"project1"})
// Add project2-scoped memory (similar content)
proj2, _, _ := s.Add("alpha beta delta", "", "", []string{"project2"})
// Add another project1 memory
proj1b, _, _ := s.Add("alpha beta epsilon", "", "", []string{"project1"})
// Global should connect to everything (it's global)
_, neighbors, _ := s.Get(global.ID)
if len(neighbors) == 0 {
t.Fatal("Global memory should have neighbors")
}
foundProj1 := false
foundProj2 := false
for _, n := range neighbors {
if n.ID == proj1.ID {
foundProj1 = true
}
if n.ID == proj2.ID {
foundProj2 = true
}
}
if !foundProj1 || !foundProj2 {
t.Fatalf("Global memory should connect to both project1 and project2. Found proj1: %v, proj2: %v", foundProj1, foundProj2)
}
// Project1 memories should connect to each other and global, but NOT project2
_, neighbors, _ = s.Get(proj1.ID)
if len(neighbors) == 0 {
t.Fatal("Project1 memory should have neighbors")
}
foundGlobal := false
foundProj1b := false
foundProj2InProj1 := false
for _, n := range neighbors {
if n.ID == global.ID {
foundGlobal = true
}
if n.ID == proj1b.ID {
foundProj1b = true
}
if n.ID == proj2.ID {
foundProj2InProj1 = true
}
}
if !foundGlobal {
t.Fatal("Project1 memory should connect to global memory")
}
if !foundProj1b {
t.Fatal("Project1 memories should connect to each other")
}
if foundProj2InProj1 {
t.Fatal("Project1 memory should NOT connect to project2 memory")
}
// Project2 should only connect to global, not project1
_, neighbors, _ = s.Get(proj2.ID)
if len(neighbors) == 0 {
t.Fatal("Project2 memory should have neighbors")
}
foundGlobalInProj2 := false
foundProj1InProj2 := false
for _, n := range neighbors {
if n.ID == global.ID {
foundGlobalInProj2 = true
}
if n.ID == proj1.ID {
foundProj1InProj2 = true
}
}
if !foundGlobalInProj2 {
t.Fatal("Project2 memory should connect to global memory")
}
if foundProj1InProj2 {
t.Fatal("Project2 memory should NOT connect to project1 memory")
}
// Search with scope filter should only return scope-compatible neighbors
matches, _ := s.Search("alpha", "", "project1")
if len(matches) == 0 {
t.Fatal("Search should find project1 memories")
}
for _, m := range matches {
// All neighbors should be project1 or global
for _, neighbor := range m.Neighbors {
nChunk, _, _ := s.Get(neighbor.ID)
if len(nChunk.Scopes) > 0 {
hasProject1 := false
for _, s := range nChunk.Scopes {
if s == "project1" {
hasProject1 = true
break
}
}
if !hasProject1 {
t.Fatalf("Neighbor %s in project1 search should be project1 or global, but has scopes: %v", neighbor.ID, nChunk.Scopes)
}
}
}
}
}
// TestMemoryStore_ConcurrentGetAndUpdate verifies that concurrent Get (which
// triggers access tracking with an async goroutine) and Update operations do
// not race. Run with -race to detect data races.
func TestMemoryStore_ConcurrentGetAndUpdate(t *testing.T) {
s := mustNewMemoryStore(t, MemoryStoreOptions{})
chunk, _, _ := s.Add("concurrent access test memory with enough tokens to be interesting", "", "", nil)
var wg sync.WaitGroup
const iterations = 50
// Concurrent Gets (each spawns an async save goroutine via trackAccessLocked).
wg.Add(iterations)
for i := 0; i < iterations; i++ {
go func() {
defer wg.Done()
_, _, _ = s.Get(chunk.ID)
}()
}
// Concurrent Updates on the same chunk.
wg.Add(iterations)
for i := 0; i < iterations; i++ {
go func(n int) {