-
Notifications
You must be signed in to change notification settings - Fork 664
Expand file tree
/
Copy pathstore_test.go
More file actions
8749 lines (7767 loc) · 282 KB
/
Copy pathstore_test.go
File metadata and controls
8749 lines (7767 loc) · 282 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 store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
_ "modernc.org/sqlite"
)
func mustDefaultConfig(t *testing.T) Config {
t.Helper()
cfg, err := DefaultConfig()
if err != nil {
t.Fatalf("DefaultConfig: %v", err)
}
return cfg
}
func newTestStore(t *testing.T) *Store {
t.Helper()
cfg := mustDefaultConfig(t)
cfg.DataDir = t.TempDir()
cfg.DedupeWindow = time.Hour
s, err := New(cfg)
if err != nil {
t.Fatalf("new store: %v", err)
}
t.Cleanup(func() {
_ = s.Close()
})
return s
}
type fakeRows struct {
next []bool
scanErr error
err error
closeErr error
closed bool
}
func (f *fakeRows) Next() bool {
if len(f.next) == 0 {
return false
}
v := f.next[0]
f.next = f.next[1:]
return v
}
func (f *fakeRows) Scan(dest ...any) error {
return f.scanErr
}
func (f *fakeRows) Err() error {
return f.err
}
func (f *fakeRows) Close() error {
f.closed = true
return f.closeErr
}
func TestAddObservationDeduplicatesWithinWindow(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
firstID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "Fixed tokenizer",
Content: "Normalized tokenizer panic on edge case",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add first observation: %v", err)
}
secondID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "Fixed tokenizer",
Content: "normalized tokenizer panic on EDGE case",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add duplicate observation: %v", err)
}
if firstID != secondID {
t.Fatalf("expected duplicate to reuse same id, got %d and %d", firstID, secondID)
}
obs, err := s.GetObservation(firstID)
if err != nil {
t.Fatalf("get deduped observation: %v", err)
}
if obs.DuplicateCount != 2 {
t.Fatalf("expected duplicate_count=2, got %d", obs.DuplicateCount)
}
}
func TestScopeFiltersSearchAndContext(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
_, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "decision",
Title: "Project auth",
Content: "Keep auth middleware in project memory",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add project observation: %v", err)
}
_, err = s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "decision",
Title: "Personal note",
Content: "Use this regex trick later",
Project: "engram",
Scope: "personal",
})
if err != nil {
t.Fatalf("add personal observation: %v", err)
}
projectResults, err := s.Search("regex", SearchOptions{Project: "engram", Scope: "project", Limit: 10})
if err != nil {
t.Fatalf("search project scope: %v", err)
}
if len(projectResults) != 0 {
t.Fatalf("expected no project-scope regex results, got %d", len(projectResults))
}
personalResults, err := s.Search("regex", SearchOptions{Project: "engram", Scope: "personal", Limit: 10})
if err != nil {
t.Fatalf("search personal scope: %v", err)
}
if len(personalResults) != 1 {
t.Fatalf("expected 1 personal-scope result, got %d", len(personalResults))
}
ctx, err := s.FormatContext("engram", "personal")
if err != nil {
t.Fatalf("format context personal: %v", err)
}
if !strings.Contains(ctx, "Personal note") {
t.Fatalf("expected personal context to include personal observation")
}
if strings.Contains(ctx, "Project auth") {
t.Fatalf("expected personal context to exclude project observation")
}
}
func TestUpdateAndSoftDeleteExcludedFromSearchAndTimeline(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
firstID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "first",
Content: "first event",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add first: %v", err)
}
middleID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "middle",
Content: "to be deleted",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add middle: %v", err)
}
lastID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "last",
Content: "last event",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add last: %v", err)
}
newTitle := "last-updated"
newContent := "updated content"
newScope := "personal"
updated, err := s.UpdateObservation(lastID, UpdateObservationParams{
Title: &newTitle,
Content: &newContent,
Scope: &newScope,
})
if err != nil {
t.Fatalf("update observation: %v", err)
}
if updated.Title != newTitle || updated.Scope != "personal" {
t.Fatalf("update did not apply; got title=%q scope=%q", updated.Title, updated.Scope)
}
if err := s.DeleteObservation(middleID, false); err != nil {
t.Fatalf("soft delete: %v", err)
}
if _, err := s.GetObservation(middleID); err == nil {
t.Fatalf("expected deleted observation to be hidden from GetObservation")
}
searchResults, err := s.Search("deleted", SearchOptions{Project: "engram", Limit: 10})
if err != nil {
t.Fatalf("search after delete: %v", err)
}
if len(searchResults) != 0 {
t.Fatalf("expected deleted observation excluded from search")
}
timeline, err := s.Timeline(firstID, 5, 5)
if err != nil {
t.Fatalf("timeline: %v", err)
}
if len(timeline.After) != 1 || timeline.After[0].ID != lastID {
t.Fatalf("expected timeline to skip deleted observation")
}
if err := s.DeleteObservation(lastID, true); err != nil {
t.Fatalf("hard delete: %v", err)
}
if _, err := s.GetObservation(lastID); err == nil {
t.Fatalf("expected hard-deleted observation to be missing")
}
}
func TestPinnedObservationsAndFormatContextPriority(t *testing.T) {
cfg := mustDefaultConfig(t)
cfg.DataDir = t.TempDir()
cfg.DedupeWindow = time.Hour
cfg.MaxContextResults = 2
s, err := New(cfg)
if err != nil {
t.Fatalf("new store: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
titles := []string{"pinned architecture", "recent one", "recent two", "recent three"}
ids := make([]int64, 0, len(titles))
for i, title := range titles {
id, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "decision",
Title: title,
Content: fmt.Sprintf("content %d", i),
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add observation %q: %v", title, err)
}
ids = append(ids, id)
createdAt := fmt.Sprintf("2026-01-0%d 00:00:00", i+1)
if _, err := s.db.Exec(`UPDATE observations SET created_at = ?, updated_at = ? WHERE id = ?`, createdAt, createdAt, id); err != nil {
t.Fatalf("set created_at for %q: %v", title, err)
}
}
exportedBeforePin, err := s.ExportProject("engram")
if err != nil {
t.Fatalf("export project before pin: %v", err)
}
exportedBeforePinJSON, err := json.Marshal(exportedBeforePin)
if err != nil {
t.Fatalf("marshal export before pin: %v", err)
}
var updatedAtBeforePin string
if err := s.db.QueryRow(`SELECT updated_at FROM observations WHERE id = ?`, ids[0]).Scan(&updatedAtBeforePin); err != nil {
t.Fatalf("get updated_at before pin: %v", err)
}
if err := s.PinObservation(ids[0]); err != nil {
t.Fatalf("pin observation: %v", err)
}
var updatedAtAfterPin string
if err := s.db.QueryRow(`SELECT updated_at FROM observations WHERE id = ?`, ids[0]).Scan(&updatedAtAfterPin); err != nil {
t.Fatalf("get updated_at after pin: %v", err)
}
if updatedAtAfterPin != updatedAtBeforePin {
t.Fatalf("pin should not change updated_at: before=%q after=%q", updatedAtBeforePin, updatedAtAfterPin)
}
pinned, err := s.PinnedObservations("engram", "project")
if err != nil {
t.Fatalf("pinned observations: %v", err)
}
if len(pinned) != 1 || pinned[0].ID != ids[0] || !pinned[0].Pinned {
t.Fatalf("expected pinned observation %d, got %#v", ids[0], pinned)
}
ctx, err := s.FormatContext("engram", "project")
if err != nil {
t.Fatalf("format context: %v", err)
}
pinnedIdx := strings.Index(ctx, "### Pinned")
recentIdx := strings.Index(ctx, "### Recent Observations")
if pinnedIdx < 0 || recentIdx < 0 || pinnedIdx > recentIdx {
t.Fatalf("expected pinned section before recent observations, got:\n%s", ctx)
}
if !strings.Contains(ctx, "pinned architecture") {
t.Fatalf("expected pinned observation in context, got:\n%s", ctx)
}
if !strings.Contains(ctx, "recent three") || !strings.Contains(ctx, "recent two") {
t.Fatalf("expected max recent unpinned observations in context, got:\n%s", ctx)
}
if strings.Contains(ctx, "recent one") {
t.Fatalf("expected recent window to stay at MaxContextResults, got:\n%s", ctx)
}
exported, err := s.ExportProject("engram")
if err != nil {
t.Fatalf("export project: %v", err)
}
exportedJSON, err := json.Marshal(exported)
if err != nil {
t.Fatalf("marshal export: %v", err)
}
if strings.Contains(string(exportedJSON), `"pinned"`) {
t.Fatalf("pinned state must stay out of sync/export JSON, got %s", exportedJSON)
}
if string(exportedJSON) != string(exportedBeforePinJSON) {
t.Fatalf("pinning must not change export payload:\nbefore: %s\nafter: %s", exportedBeforePinJSON, exportedJSON)
}
if err := s.UnpinObservation(ids[0]); err != nil {
t.Fatalf("unpin observation: %v", err)
}
var updatedAtAfterUnpin string
if err := s.db.QueryRow(`SELECT updated_at FROM observations WHERE id = ?`, ids[0]).Scan(&updatedAtAfterUnpin); err != nil {
t.Fatalf("get updated_at after unpin: %v", err)
}
if updatedAtAfterUnpin != updatedAtBeforePin {
t.Fatalf("unpin should not change updated_at: before=%q after=%q", updatedAtBeforePin, updatedAtAfterUnpin)
}
pinned, err = s.PinnedObservations("engram", "project")
if err != nil {
t.Fatalf("pinned observations after unpin: %v", err)
}
if len(pinned) != 0 {
t.Fatalf("expected no pinned observations after unpin, got %#v", pinned)
}
}
func TestTopicKeyUpsertUpdatesSameTopicWithoutCreatingNewRow(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
firstID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "architecture",
Title: "Auth architecture",
Content: "Use middleware for JWT validation.",
Project: "engram",
Scope: "project",
TopicKey: "architecture auth model",
})
if err != nil {
t.Fatalf("add first architecture: %v", err)
}
secondID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "architecture",
Title: "Auth architecture",
Content: "Move auth to gateway + middleware chain.",
Project: "engram",
Scope: "project",
TopicKey: "ARCHITECTURE AUTH MODEL",
})
if err != nil {
t.Fatalf("upsert architecture: %v", err)
}
if firstID != secondID {
t.Fatalf("expected topic upsert to reuse id, got %d and %d", firstID, secondID)
}
obs, err := s.GetObservation(firstID)
if err != nil {
t.Fatalf("get upserted observation: %v", err)
}
if obs.RevisionCount != 2 {
t.Fatalf("expected revision_count=2, got %d", obs.RevisionCount)
}
if obs.TopicKey == nil || *obs.TopicKey != "architecture-auth-model" {
t.Fatalf("expected normalized topic key, got %v", obs.TopicKey)
}
if !strings.Contains(obs.Content, "gateway") {
t.Fatalf("expected latest content after upsert, got %q", obs.Content)
}
}
func TestDifferentTopicsDoNotReplaceEachOther(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
archID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "architecture",
Title: "Auth architecture",
Content: "Architecture decision",
Project: "engram",
Scope: "project",
TopicKey: "architecture/auth",
})
if err != nil {
t.Fatalf("add architecture observation: %v", err)
}
bugID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "Fix auth nil panic",
Content: "Bugfix details",
Project: "engram",
Scope: "project",
TopicKey: "bug/auth-nil-panic",
})
if err != nil {
t.Fatalf("add bug observation: %v", err)
}
if archID == bugID {
t.Fatalf("expected different topic keys to create different observations")
}
observations, err := s.AllObservations("engram", "project", 10)
if err != nil {
t.Fatalf("all observations: %v", err)
}
if len(observations) != 2 {
t.Fatalf("expected 2 observations, got %d", len(observations))
}
}
func TestNewMigratesLegacyObservationIDSchema(t *testing.T) {
dataDir := t.TempDir()
dbPath := filepath.Join(dataDir, "engram.db")
db, err := sql.Open("sqlite", dbPath)
if err != nil {
t.Fatalf("open legacy db: %v", err)
}
_, err = db.Exec(`
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
project TEXT NOT NULL,
directory TEXT NOT NULL,
started_at TEXT NOT NULL DEFAULT (datetime('now')),
ended_at TEXT,
summary TEXT
);
CREATE TABLE observations (
id INT,
session_id TEXT,
type TEXT,
title TEXT,
content TEXT,
tool_name TEXT,
project TEXT,
created_at TEXT
);
INSERT INTO sessions (id, project, directory) VALUES ('s1', 'engram', '/tmp/engram');
INSERT INTO observations (id, session_id, type, title, content, project, created_at)
VALUES
(NULL, 's1', 'bugfix', 'legacy null', 'legacy null content', 'engram', datetime('now')),
(7, 's1', 'bugfix', 'legacy fixed', 'legacy fixed content', 'engram', datetime('now')),
(7, 's1', 'bugfix', 'legacy duplicate', 'legacy duplicate content', 'engram', datetime('now'));
`)
if err != nil {
_ = db.Close()
t.Fatalf("seed legacy db: %v", err)
}
if err := db.Close(); err != nil {
t.Fatalf("close legacy db: %v", err)
}
cfg := mustDefaultConfig(t)
cfg.DataDir = dataDir
s, err := New(cfg)
if err != nil {
t.Fatalf("new store after legacy schema: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
obs, err := s.AllObservations("engram", "", 20)
if err != nil {
t.Fatalf("all observations after migration: %v", err)
}
if len(obs) != 3 {
t.Fatalf("expected 3 migrated observations, got %d", len(obs))
}
seen := make(map[int64]bool)
for _, o := range obs {
if o.ID <= 0 {
t.Fatalf("expected migrated observation id > 0, got %d", o.ID)
}
if seen[o.ID] {
t.Fatalf("expected unique migrated ids, duplicate %d", o.ID)
}
seen[o.ID] = true
}
results, err := s.Search("legacy", SearchOptions{Project: "engram", Limit: 10})
if err != nil {
t.Fatalf("search after migration: %v", err)
}
if len(results) == 0 {
t.Fatalf("expected search results after migration")
}
newID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "bugfix",
Title: "post migration",
Content: "new row should get id",
Project: "engram",
Scope: "project",
})
if err != nil {
t.Fatalf("add observation after migration: %v", err)
}
if newID <= 0 {
t.Fatalf("expected autoincrement id after migration, got %d", newID)
}
}
func TestNewMigratesLegacyUserPromptsSyncIDSchema(t *testing.T) {
dataDir := t.TempDir()
dbPath := filepath.Join(dataDir, "engram.db")
db, err := sql.Open("sqlite", dbPath)
if err != nil {
t.Fatalf("open legacy db: %v", err)
}
_, err = db.Exec(`
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
project TEXT NOT NULL,
directory TEXT NOT NULL,
started_at TEXT NOT NULL DEFAULT (datetime('now')),
ended_at TEXT,
summary TEXT
);
CREATE TABLE user_prompts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
content TEXT NOT NULL,
project TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(id)
);
INSERT INTO sessions (id, project, directory) VALUES ('s1', 'engram', '/tmp/engram');
INSERT INTO user_prompts (session_id, content, project) VALUES ('s1', 'legacy prompt', 'engram');
`)
if err != nil {
_ = db.Close()
t.Fatalf("seed legacy db: %v", err)
}
if err := db.Close(); err != nil {
t.Fatalf("close legacy db: %v", err)
}
cfg := mustDefaultConfig(t)
cfg.DataDir = dataDir
s, err := New(cfg)
if err != nil {
t.Fatalf("new store after legacy prompt schema: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
var syncID string
if err := s.db.QueryRow("SELECT sync_id FROM user_prompts WHERE content = ?", "legacy prompt").Scan(&syncID); err != nil {
t.Fatalf("query migrated prompt sync_id: %v", err)
}
if syncID == "" {
t.Fatalf("expected migrated prompt sync_id to be backfilled")
}
var hasSyncIDColumn bool
rows, err := s.db.Query("PRAGMA table_info(user_prompts)")
if err != nil {
t.Fatalf("query prompt columns: %v", err)
}
for rows.Next() {
var cid int
var name, columnType string
var notNull, pk int
var defaultValue any
if err := rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &pk); err != nil {
t.Fatalf("scan prompt column: %v", err)
}
if name == "sync_id" {
hasSyncIDColumn = true
break
}
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatalf("iterate prompt columns: %v", err)
}
if err := rows.Close(); err != nil {
t.Fatalf("close prompt columns: %v", err)
}
if !hasSyncIDColumn {
t.Fatalf("expected user_prompts.sync_id column after migration")
}
var indexName string
if err := s.db.QueryRow("SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_prompts_sync_id'").Scan(&indexName); err != nil {
t.Fatalf("query prompt sync index: %v", err)
}
if indexName != "idx_prompts_sync_id" {
t.Fatalf("expected idx_prompts_sync_id to exist, got %q", indexName)
}
}
func TestSuggestTopicKeyNormalizesDeterministically(t *testing.T) {
got := SuggestTopicKey("Architecture", " Auth Model ", "ignored")
if got != "architecture/auth-model" {
t.Fatalf("expected architecture/auth-model, got %q", got)
}
fallback := SuggestTopicKey("bugfix", "", "Fix nil panic in auth middleware on empty token")
if fallback != "bug/fix-nil-panic-in-auth-middleware-on-empty" {
t.Fatalf("unexpected fallback topic key: %q", fallback)
}
}
func TestSuggestTopicKeyInfersFamilyFromTextWhenTypeIsGeneric(t *testing.T) {
bug := SuggestTopicKey("manual", "", "Fix regression in auth login flow")
if bug != "bug/fix-regression-in-auth-login-flow" {
t.Fatalf("expected bug family inference, got %q", bug)
}
arch := SuggestTopicKey("", "ADR: Split API gateway boundary", "")
if arch != "architecture/adr-split-api-gateway-boundary" {
t.Fatalf("expected architecture family inference, got %q", arch)
}
}
func TestTopicKeyUpsertIsScopedByProjectAndScope(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
baseID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "architecture",
Title: "Auth model",
Content: "Initial architecture",
Project: "engram",
Scope: "project",
TopicKey: "architecture/auth-model",
})
if err != nil {
t.Fatalf("add base observation: %v", err)
}
personalID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "architecture",
Title: "Auth model",
Content: "Personal take",
Project: "engram",
Scope: "personal",
TopicKey: "architecture/auth-model",
})
if err != nil {
t.Fatalf("add personal scoped observation: %v", err)
}
otherProjectID, err := s.AddObservation(AddObservationParams{
SessionID: "s1",
Type: "architecture",
Title: "Auth model",
Content: "Other project",
Project: "another-project",
Scope: "project",
TopicKey: "architecture/auth-model",
})
if err != nil {
t.Fatalf("add other project observation: %v", err)
}
if baseID == personalID || baseID == otherProjectID || personalID == otherProjectID {
t.Fatalf("expected topic upsert boundaries by project+scope, got ids base=%d personal=%d other=%d", baseID, personalID, otherProjectID)
}
}
func TestPromptProjectNullScan(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("s1", "engram", "/tmp/engram"); err != nil {
t.Fatalf("create session: %v", err)
}
// Manually insert a prompt with NULL project to simulate legacy data or external changes
_, err := s.db.Exec(
"INSERT INTO user_prompts (session_id, content, project) VALUES (?, ?, NULL)",
"s1", "prompt with null project",
)
if err != nil {
t.Fatalf("manual insert: %v", err)
}
// 1. Test RecentPrompts
prompts, err := s.RecentPrompts("", 10)
if err != nil {
t.Fatalf("RecentPrompts failed with null project: %v", err)
}
if len(prompts) != 1 || prompts[0].Project != "" {
t.Errorf("expected empty string for null project, got %q", prompts[0].Project)
}
// 2. Test SearchPrompts
searchResult, err := s.SearchPrompts("null", "", 10)
if err != nil {
t.Fatalf("SearchPrompts failed with null project: %v", err)
}
if len(searchResult) != 1 || searchResult[0].Project != "" {
t.Errorf("expected empty string for null project in search, got %q", searchResult[0].Project)
}
// 3. Test Export
data, err := s.Export()
if err != nil {
t.Fatalf("Export failed with null project: %v", err)
}
found := false
for _, p := range data.Prompts {
if p.Content == "prompt with null project" {
found = true
if p.Project != "" {
t.Errorf("expected empty string for null project in export, got %q", p.Project)
}
}
}
if !found {
t.Error("exported prompts missing the test prompt")
}
}
func TestExportProjectScopesRowsWithoutGlobalDumpFiltering(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("sess-a", "proj-a", "/tmp/proj-a"); err != nil {
t.Fatalf("create session proj-a: %v", err)
}
if err := s.CreateSession("sess-b", "proj-b", "/tmp/proj-b"); err != nil {
t.Fatalf("create session proj-b: %v", err)
}
if _, err := s.AddObservation(AddObservationParams{SessionID: "sess-a", Type: "note", Title: "a", Content: "a", Project: "proj-a", Scope: "project"}); err != nil {
t.Fatalf("add obs proj-a: %v", err)
}
if _, err := s.AddObservation(AddObservationParams{SessionID: "sess-b", Type: "note", Title: "b", Content: "b", Project: "proj-b", Scope: "project"}); err != nil {
t.Fatalf("add obs proj-b: %v", err)
}
if _, err := s.AddPrompt(AddPromptParams{SessionID: "sess-a", Content: "prompt-a", Project: "proj-a"}); err != nil {
t.Fatalf("add prompt proj-a: %v", err)
}
if _, err := s.AddPrompt(AddPromptParams{SessionID: "sess-b", Content: "prompt-b", Project: "proj-b"}); err != nil {
t.Fatalf("add prompt proj-b: %v", err)
}
data, err := s.ExportProject("proj-a")
if err != nil {
t.Fatalf("ExportProject: %v", err)
}
if len(data.Sessions) != 1 || data.Sessions[0].Project != "proj-a" {
t.Fatalf("expected only proj-a sessions, got %+v", data.Sessions)
}
if len(data.Observations) != 1 || data.Observations[0].SessionID != "sess-a" {
t.Fatalf("expected only proj-a observations, got %+v", data.Observations)
}
if len(data.Prompts) != 1 || data.Prompts[0].SessionID != "sess-a" {
t.Fatalf("expected only proj-a prompts, got %+v", data.Prompts)
}
}
func TestExportProjectPreservesSessionReferentialClosure(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("sess-owned-by-proj-b", "proj-b", "/tmp/proj-b"); err != nil {
t.Fatalf("create session proj-b: %v", err)
}
if _, err := s.AddObservation(AddObservationParams{
SessionID: "sess-owned-by-proj-b",
Type: "note",
Title: "cross-project obs",
Content: "observation references proj-b session",
Project: "proj-a",
Scope: "project",
}); err != nil {
t.Fatalf("add cross-project observation: %v", err)
}
if _, err := s.AddPrompt(AddPromptParams{
SessionID: "sess-owned-by-proj-b",
Content: "cross-project prompt",
Project: "proj-a",
}); err != nil {
t.Fatalf("add cross-project prompt: %v", err)
}
exported, err := s.ExportProject("proj-a")
if err != nil {
t.Fatalf("ExportProject: %v", err)
}
if len(exported.Observations) != 1 || len(exported.Prompts) != 1 {
t.Fatalf("expected one cross-project observation and prompt, got obs=%d prompts=%d", len(exported.Observations), len(exported.Prompts))
}
foundReferencedSession := false
for _, sess := range exported.Sessions {
if sess.ID == "sess-owned-by-proj-b" {
foundReferencedSession = true
break
}
}
if !foundReferencedSession {
t.Fatalf("expected export to include referenced session sess-owned-by-proj-b for referential closure")
}
dstCfg := mustDefaultConfig(t)
dstCfg.DataDir = t.TempDir()
dst, err := New(dstCfg)
if err != nil {
t.Fatalf("new destination store: %v", err)
}
t.Cleanup(func() { _ = dst.Close() })
if _, err := dst.Import(exported); err != nil {
t.Fatalf("import exported project data should succeed with referential closure: %v", err)
}
}
func TestExportProjectDoesNotLeakRowsOwnedByOtherProjectsViaSessionMembership(t *testing.T) {
s := newTestStore(t)
if err := s.CreateSession("sess-proj-a", "proj-a", "/tmp/proj-a"); err != nil {
t.Fatalf("create session proj-a: %v", err)
}
if _, err := s.AddObservation(AddObservationParams{
SessionID: "sess-proj-a",
Type: "note",
Title: "owned-by-proj-b",
Content: "should not leak in proj-a export",
Project: "proj-b",
Scope: "project",
}); err != nil {
t.Fatalf("add cross-owned observation: %v", err)
}
if _, err := s.AddPrompt(AddPromptParams{
SessionID: "sess-proj-a",
Content: "prompt owned by proj-b",
Project: "proj-b",
}); err != nil {
t.Fatalf("add cross-owned prompt: %v", err)
}
if _, err := s.AddObservation(AddObservationParams{
SessionID: "sess-proj-a",
Type: "note",
Title: "projectless observation",
Content: "derive ownership from proj-a session",
Scope: "project",
}); err != nil {
t.Fatalf("add projectless observation: %v", err)
}
if _, err := s.AddPrompt(AddPromptParams{
SessionID: "sess-proj-a",
Content: "projectless prompt",
}); err != nil {
t.Fatalf("add projectless prompt: %v", err)
}
exported, err := s.ExportProject("proj-a")
if err != nil {
t.Fatalf("ExportProject: %v", err)
}
if len(exported.Observations) != 1 {
t.Fatalf("expected only project-owned/projectless-derived observations, got %+v", exported.Observations)
}
if exported.Observations[0].Title != "projectless observation" {
t.Fatalf("expected only projectless-derived observation, got %+v", exported.Observations[0])
}
if len(exported.Prompts) != 1 {
t.Fatalf("expected only project-owned/projectless-derived prompts, got %+v", exported.Prompts)
}
if exported.Prompts[0].Content != "projectless prompt" {
t.Fatalf("expected only projectless-derived prompt, got %+v", exported.Prompts[0])
}
}
// ─── Passive Capture Tests ───────────────────────────────────────────────────
func TestExtractLearningsNumberedList(t *testing.T) {
text := `Some preamble text here.
## Key Learnings:
1. bcrypt cost=12 is the right balance for our server performance
2. JWT refresh tokens need atomic rotation to prevent race conditions
3. Always validate the audience claim in JWT tokens before trusting them
## Next Steps
- something else
`
learnings := ExtractLearnings(text)
if len(learnings) != 3 {
t.Fatalf("expected 3 learnings, got %d: %v", len(learnings), learnings)
}
if !strings.Contains(learnings[0], "bcrypt") {
t.Fatalf("expected first learning about bcrypt, got %q", learnings[0])
}
}
func TestExtractLearningsSpanishHeader(t *testing.T) {
text := `## Aprendizajes Clave:
1. El costo de bcrypt=12 es el balance correcto para nuestro servidor
2. Los refresh tokens de JWT necesitan rotacion atomica
`
learnings := ExtractLearnings(text)
if len(learnings) != 2 {
t.Fatalf("expected 2 learnings, got %d: %v", len(learnings), learnings)
}
}
func TestExtractLearningsBulletList(t *testing.T) {
text := `### Learnings:
- bcrypt cost=12 is the right balance for our server performance
- JWT refresh tokens need atomic rotation to prevent race conditions
`
learnings := ExtractLearnings(text)
if len(learnings) != 2 {
t.Fatalf("expected 2 learnings, got %d: %v", len(learnings), learnings)
}