Repository navigation
Expand file tree
/
Copy pathmemorySystem.integration.test.ts
More file actions
1347 lines (1199 loc) · 45.5 KB
/
Copy pathmemorySystem.integration.test.ts
File metadata and controls
1347 lines (1199 loc) · 45.5 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
import { generateText } from "ai";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// Import after mocks are set up
import type { UIMessage } from "../../../utils/messageTypes";
import type { SubscriptionPlan } from "../../subscriptionPlans";
import type { FactRecord, TemporalGrain } from "../../vectordb/types";
import type { AugmentedContext } from "../../workspaceCreditContext";
import { calculateRetentionCutoff } from "../retentionPolicies";
import { searchMemory } from "../searchMemory";
import { summarizeWithLLM } from "../summarizeMemory";
import { formatTimeForGrain } from "../timeFormats";
import { writeToWorkingMemory, queueMemoryWrite } from "../writeMemory";
// Mock dependencies using vi.hoisted
const {
mockGenerateEmbedding,
mockGenerateEmbeddingWithUsage,
mockResolveEmbeddingApiKey,
mockSendWriteOperation,
mockQuery,
mockGetWorkspaceApiKey,
mockCreateModel,
mockValidateCreditsAndLimitsAndReserve,
mockAdjustCreditsAfterLLMCall,
mockCleanupReservationOnError,
mockCleanupReservationWithoutTokenUsage,
mockEnqueueCostVerificationIfNeeded,
mockExtractTokenUsageAndCosts,
mockDatabase,
} = vi.hoisted(() => {
return {
mockGenerateEmbedding: vi.fn(),
mockGenerateEmbeddingWithUsage: vi.fn(),
mockResolveEmbeddingApiKey: vi.fn(),
mockSendWriteOperation: vi.fn(),
mockQuery: vi.fn(),
mockGetWorkspaceApiKey: vi.fn(),
mockCreateModel: vi.fn(),
mockValidateCreditsAndLimitsAndReserve: vi.fn(),
mockAdjustCreditsAfterLLMCall: vi.fn(),
mockCleanupReservationOnError: vi.fn(),
mockCleanupReservationWithoutTokenUsage: vi.fn(),
mockEnqueueCostVerificationIfNeeded: vi.fn(),
mockExtractTokenUsageAndCosts: vi.fn(),
mockDatabase: vi.fn(),
};
});
// Mock modules
vi.mock("../../../http/utils/agentUtils", () => ({
getWorkspaceApiKey: mockGetWorkspaceApiKey,
}));
vi.mock("../../../http/utils/agent-keys", () => ({
getWorkspaceApiKey: mockGetWorkspaceApiKey,
}));
vi.mock("../../embedding", () => ({
generateEmbedding: mockGenerateEmbedding,
generateEmbeddingWithUsage: mockGenerateEmbeddingWithUsage,
resolveEmbeddingApiKey: mockResolveEmbeddingApiKey,
}));
vi.mock("../../vectordb/queueClient", () => ({
sendWriteOperation: mockSendWriteOperation,
}));
vi.mock("../../vectordb/readClient", () => ({
query: mockQuery,
}));
vi.mock("../../vectordb/config", () => ({
getS3BucketName: () => "test-bucket",
DEFAULT_S3_REGION: "eu-west-2",
MAX_QUERY_LIMIT: 1000,
getS3ConnectionOptions: vi.fn().mockReturnValue({
region: "eu-west-2",
}),
}));
vi.mock("../../../http/utils/modelFactory", () => ({
createModel: mockCreateModel,
getDefaultModel: () => "google/gemini-2.5-flash",
}));
vi.mock("ai", async () => {
const actual = await vi.importActual("ai");
return {
...actual,
generateText: vi.fn(),
};
});
vi.mock("../../../tables", () => ({
database: mockDatabase,
}));
vi.mock("../../../http/utils/generationCreditManagement", () => ({
adjustCreditsAfterLLMCall: mockAdjustCreditsAfterLLMCall,
cleanupReservationOnError: mockCleanupReservationOnError,
cleanupReservationWithoutTokenUsage: mockCleanupReservationWithoutTokenUsage,
enqueueCostVerificationIfNeeded: mockEnqueueCostVerificationIfNeeded,
}));
vi.mock("../../../http/utils/generationTokenExtraction", () => ({
extractTokenUsageAndCosts: mockExtractTokenUsageAndCosts,
}));
vi.mock("../../creditValidation", () => ({
validateCreditsAndLimitsAndReserve: mockValidateCreditsAndLimitsAndReserve,
}));
describe("Memory System Integration", () => {
const agentId = "test-agent-123";
const workspaceId = "test-workspace-456";
const subscriptionPlan: SubscriptionPlan = "pro";
// In-memory storage for each grain, organized by time string
const memoryStorage: Record<TemporalGrain, Map<string, FactRecord[]>> = {
working: new Map(),
daily: new Map(),
weekly: new Map(),
monthly: new Map(),
quarterly: new Map(),
yearly: new Map(),
docs: new Map(), // Documents grain (not used in memory system, but required for type)
};
// Track all SQS operations for verification
const sqsOperations: Array<{
operation: string;
agentId: string;
grain: TemporalGrain;
records?: FactRecord[];
recordIds?: string[];
}> = [];
// Helper to get all records for a grain
function getAllRecordsForGrain(grain: TemporalGrain): FactRecord[] {
return Array.from(memoryStorage[grain].values()).flat();
}
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
// Set environment variable for API key
process.env.OPENROUTER_API_KEY = "test-api-key";
// Clear storage
Object.values(memoryStorage).forEach((map) => map.clear());
sqsOperations.length = 0;
// Mock workspace API key
mockGetWorkspaceApiKey.mockResolvedValue(null);
mockResolveEmbeddingApiKey.mockResolvedValue({
apiKey: "test-api-key",
usesByok: false,
});
mockDatabase.mockResolvedValue({});
mockValidateCreditsAndLimitsAndReserve.mockResolvedValue(null);
mockExtractTokenUsageAndCosts.mockReturnValue({
tokenUsage: undefined,
openrouterGenerationId: undefined,
openrouterGenerationIds: [],
provisionalCostUsd: undefined,
});
// Mock model creation
mockCreateModel.mockResolvedValue({
// Mock model object
});
// Mock embedding generation - return deterministic embeddings
mockGenerateEmbedding.mockImplementation(async (text: string) => {
// Generate a simple deterministic embedding based on text hash
const hash = text
.split("")
.reduce((acc, char) => acc + char.charCodeAt(0), 0);
const embedding = Array.from({ length: 768 }, (_, i) => {
return ((hash + i) % 100) / 1000; // Simple deterministic embedding
});
return Promise.resolve(embedding);
});
mockGenerateEmbeddingWithUsage.mockImplementation(async (text: string) => {
const embedding = await mockGenerateEmbedding(text);
return {
embedding,
usage: {
promptTokens: 10,
totalTokens: 10,
cost: 0.000001,
},
id: `embedding-${text.length}`,
fromCache: false,
};
});
// Mock SQS write operation - store in memory
// For rawFacts, generate embeddings (simulated)
mockSendWriteOperation.mockImplementation(
async (message: {
operation: string;
agentId: string;
temporalGrain: TemporalGrain;
workspaceId?: string;
data: {
records?: FactRecord[];
rawFacts?: Array<{
id: string;
content: string;
timestamp: string;
metadata?: Record<string, unknown>;
cacheKey?: string;
}>;
recordIds?: string[];
};
}) => {
sqsOperations.push({
operation: message.operation,
agentId: message.agentId,
grain: message.temporalGrain,
records: message.data.records,
recordIds: message.data.recordIds,
});
if (message.operation === "insert" || message.operation === "update") {
let recordsToStore: FactRecord[] = [];
// If rawFacts are provided, generate embeddings for them
if (message.data.rawFacts && message.data.rawFacts.length > 0) {
for (const rawFact of message.data.rawFacts) {
// Generate embedding using the mock
const embedding = await mockGenerateEmbedding(rawFact.content);
recordsToStore.push({
id: rawFact.id,
content: rawFact.content,
embedding,
timestamp: rawFact.timestamp,
metadata: rawFact.metadata,
});
}
} else if (message.data.records) {
// Use pre-generated records
recordsToStore = message.data.records;
}
// Store records in memory
for (const record of recordsToStore) {
const timeKey =
message.temporalGrain === "working"
? "global"
: (record.metadata?.timeString as string) || "default";
if (!memoryStorage[message.temporalGrain].has(timeKey)) {
memoryStorage[message.temporalGrain].set(timeKey, []);
}
const existing =
memoryStorage[message.temporalGrain].get(timeKey) || [];
const filtered =
message.operation === "update"
? existing.filter((item) => item.id !== record.id)
: existing;
// Create a new array to avoid reference issues
const updated = [...filtered, record];
memoryStorage[message.temporalGrain].set(timeKey, updated);
}
} else if (message.operation === "delete" && message.data.recordIds) {
// Delete records by ID
for (const [timeKey, records] of memoryStorage[
message.temporalGrain
].entries()) {
const filtered = records.filter(
(r: FactRecord) => !message.data.recordIds!.includes(r.id),
);
if (filtered.length > 0) {
memoryStorage[message.temporalGrain].set(timeKey, filtered);
} else {
memoryStorage[message.temporalGrain].delete(timeKey);
}
}
}
},
);
// Mock vector DB query - return records from memory storage
mockQuery.mockImplementation(
async (
queryAgentId: string,
grain: TemporalGrain,
options?: {
limit?: number;
temporalFilter?: { startDate?: string; endDate?: string };
vector?: number[];
},
) => {
if (queryAgentId !== agentId) {
return [];
}
// Get all records for this grain
const allRecords: FactRecord[] = [];
for (const records of memoryStorage[grain].values()) {
allRecords.push(...records);
}
// Apply temporal filter if provided
let filtered = allRecords;
if (options?.temporalFilter) {
const { startDate, endDate } = options.temporalFilter;
filtered = allRecords.filter((record) => {
const timestamp = new Date(record.timestamp);
if (startDate && timestamp < new Date(startDate)) {
return false;
}
if (endDate && timestamp > new Date(endDate)) {
return false;
}
return true;
});
}
// Apply limit
const limit = options?.limit || 100;
return filtered.slice(0, limit);
},
);
// Mock LLM summarization - create realistic summaries that preserve key information
vi.mocked(generateText).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- generateText has complex types
async (params: any) => {
const system = (params.system as string) || "";
const messages =
(params.messages as Array<{ role: string; content: string }>) || [];
// Return immediately (no actual async delay)
const userMessage = messages.find(
(m: { role: string; content: string }) => m.role === "user",
);
const content = (userMessage?.content as string) || "";
// Extract key information from content
const lines = content.split("\n\n---\n\n");
const facts: string[] = [];
const people: Set<string> = new Set();
const events: string[] = [];
// Extract important facts, people, and events
for (const line of lines) {
const lowerLine = line.toLowerCase();
// Extract people names (simple heuristic)
if (
lowerLine.includes("john") ||
lowerLine.includes("sarah") ||
lowerLine.includes("alice") ||
lowerLine.includes("bob")
) {
if (lowerLine.includes("john")) people.add("John");
if (lowerLine.includes("sarah")) people.add("Sarah");
if (lowerLine.includes("alice")) people.add("Alice");
if (lowerLine.includes("bob")) people.add("Bob");
}
// Extract events
if (
lowerLine.includes("meeting") ||
lowerLine.includes("discussion") ||
lowerLine.includes("project")
) {
if (lowerLine.includes("meeting")) events.push("meeting");
if (lowerLine.includes("discussion")) events.push("discussion");
if (lowerLine.includes("project")) events.push("project work");
}
if (line.includes("User said:") || line.includes("Assistant said:")) {
const fact = line
.replace(/User said: /, "")
.replace(/Assistant said: /, "")
.trim();
if (fact.length > 0) {
facts.push(fact);
}
}
}
// Create summary based on grain type with progressive abstraction
// Check system prompt for grain type keywords (check in order from most specific to least)
const systemLower = system.toLowerCase();
// Check for specific phrases that uniquely identify each grain type
// Order matters - check most specific first
if (systemLower.includes("year's worth of quarterly summaries")) {
return {
text: `Yearly Summary: Comprehensive overview of ${facts.length} events throughout the year. Major achievements, team growth, and significant project milestones.`,
} as Awaited<ReturnType<typeof generateText>>;
} else if (
systemLower.includes("quarter's worth of monthly summaries")
) {
return {
text: `Quarterly Summary: High-level overview of ${facts.length} events. Major themes: team collaboration, project development, and knowledge sharing. Key milestones achieved.`,
} as Awaited<ReturnType<typeof generateText>>;
} else if (systemLower.includes("month's worth of weekly summaries")) {
return {
text: `Monthly Summary: Overview of ${
facts.length
} events throughout the month. Key patterns: ${
events.join(", ") || "consistent collaboration"
}. Active participants: ${
Array.from(people).join(", ") || "team"
}. Notable achievements and ongoing projects.`,
} as Awaited<ReturnType<typeof generateText>>;
} else if (systemLower.includes("week's worth of daily summaries")) {
return {
text: `Weekly Summary: ${
facts.length
} significant interactions across the week. Major themes: ${
events.join(", ") || "collaboration and development"
}. Key participants: ${
Array.from(people).join(", ") || "team members"
}. Notable progress on project milestones.`,
} as Awaited<ReturnType<typeof generateText>>;
} else if (systemLower.includes("daily events from working memory")) {
// Default to daily summary
const peopleList = Array.from(people).join(", ");
return {
text: `Daily Summary (${
facts.length
} interactions): Key events included ${
events.slice(0, 3).join(", ") || "various activities"
}. Important people: ${
peopleList || "team members"
}. Main topics: ${
facts.slice(0, 3).join("; ") || "general discussion"
}.`,
} as Awaited<ReturnType<typeof generateText>>;
} else {
// Fallback: default to daily summary
const peopleList = Array.from(people).join(", ");
return {
text: `Daily Summary (${
facts.length
} interactions): Key events included ${
events.slice(0, 3).join(", ") || "various activities"
}. Important people: ${
peopleList || "team members"
}. Main topics: ${
facts.slice(0, 3).join("; ") || "general discussion"
}.`,
} as Awaited<ReturnType<typeof generateText>>;
}
},
);
});
it("charges memory extraction with reservation and verification", async () => {
const context = {
addWorkspaceCreditTransaction: vi.fn(),
} as unknown as AugmentedContext;
const mockText = JSON.stringify({
summary: "Summary text",
memory_operations: [],
});
vi.mocked(generateText).mockResolvedValue({
text: mockText,
} as Awaited<ReturnType<typeof generateText>>);
mockValidateCreditsAndLimitsAndReserve.mockResolvedValue({
reservationId: "reservation-1",
reservedAmount: 100,
workspace: { creditBalance: 0, currency: "usd" },
});
mockExtractTokenUsageAndCosts.mockReturnValue({
tokenUsage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
openrouterGenerationId: "gen-1",
openrouterGenerationIds: ["gen-1"],
provisionalCostUsd: 100,
});
await writeToWorkingMemory(
agentId,
workspaceId,
"conv-memory-charge",
[
{
role: "user",
content: "Hello, I'm John.",
},
],
{ enabled: true, modelName: "openrouter/gemini", prompt: null },
context,
);
expect(mockValidateCreditsAndLimitsAndReserve).toHaveBeenCalled();
expect(mockAdjustCreditsAfterLLMCall).toHaveBeenCalled();
expect(mockEnqueueCostVerificationIfNeeded).toHaveBeenCalled();
});
afterEach(() => {
vi.useRealTimers();
});
it("should simulate complete memory lifecycle: conversations → working → day → week → month → quarter → year with retention", async () => {
// ============================================
// PHASE 1: Initial Conversations (Week 1)
// ============================================
const week1Start = new Date("2024-01-15T10:00:00Z"); // Monday, Jan 15
vi.setSystemTime(week1Start);
// Day 1 conversations
const day1Conversations: Array<{ id: string; messages: UIMessage[] }> = [
{
id: "conv-day1-1",
messages: [
{
role: "user",
content: "Hello, I'm John. I need help with my React project.",
},
{
role: "assistant",
content:
"Hi John! I'd be happy to help with your React project. What specific aspect do you need assistance with?",
},
{
role: "user",
content: "I'm having trouble with state management using hooks.",
},
{
role: "assistant",
content:
"State management with hooks can be tricky. Are you using useState, useReducer, or a state management library?",
},
],
},
{
id: "conv-day1-2",
messages: [
{
role: "user",
content: "I met with Sarah today to discuss the project timeline.",
},
{
role: "assistant",
content:
"That sounds productive! What did you and Sarah decide about the timeline?",
},
],
},
];
// Write conversations to working memory
for (const conv of day1Conversations) {
await writeToWorkingMemory(agentId, workspaceId, conv.id, conv.messages);
}
// Verify working memory
const workingRecordsAfterDay1 = getAllRecordsForGrain("working");
expect(workingRecordsAfterDay1.length).toBeGreaterThan(0);
expect(
workingRecordsAfterDay1.some((r: FactRecord) =>
r.content.includes("John"),
),
).toBe(true);
expect(
workingRecordsAfterDay1.some((r: FactRecord) =>
r.content.includes("Sarah"),
),
).toBe(true);
// Day 2 conversations
vi.setSystemTime(new Date("2024-01-16T14:00:00Z"));
const day2Conversations: Array<{ id: string; messages: UIMessage[] }> = [
{
id: "conv-day2-1",
messages: [
{
role: "user",
content: "Sarah and I finalized the project requirements.",
},
{
role: "assistant",
content:
"Great! Having clear requirements is essential. What are the main features you'll be building?",
},
],
},
];
for (const conv of day2Conversations) {
await writeToWorkingMemory(agentId, workspaceId, conv.id, conv.messages);
}
// Day 3-7: Add more conversations to build up a week
for (let day = 3; day <= 7; day++) {
vi.setSystemTime(new Date(`2024-01-${14 + day}T10:00:00Z`));
const conv: UIMessage[] = [
{
role: "user",
content: `Day ${day}: Continued work on the React project. Discussed with team members.`,
},
{
role: "assistant",
content: `That's great progress! Keep up the good work on day ${day}.`,
},
];
await writeToWorkingMemory(
agentId,
workspaceId,
`conv-day${day}-1`,
conv,
);
}
// ============================================
// PHASE 2: Daily Summarization (End of Week 1)
// ============================================
// Advance to Day 8 (start of Week 2) to trigger daily summarization
vi.setSystemTime(new Date("2024-01-22T00:00:00Z"));
// Summarize Day 1 working memory into day summary
const day1WorkingMemory = await mockQuery(agentId, "working", {
limit: 1000,
temporalFilter: {
startDate: new Date("2024-01-15T00:00:00Z").toISOString(),
endDate: new Date("2024-01-15T23:59:59Z").toISOString(),
},
});
expect(day1WorkingMemory.length).toBeGreaterThan(0);
const day1Content = day1WorkingMemory.map((r: FactRecord) => r.content);
const day1Summary = await summarizeWithLLM(
day1Content,
"daily",
workspaceId,
agentId,
);
expect(day1Summary).toContain("Daily Summary");
expect(day1Summary).toContain("John");
expect(day1Summary).toContain("Sarah");
// Create day summary record
const day1Embedding = await mockGenerateEmbedding(day1Summary);
const day1TimeString = formatTimeForGrain("daily", new Date("2024-01-15"));
const day1Record: FactRecord = {
id: `day-${day1TimeString}-summary`,
content: day1Summary,
embedding: day1Embedding,
timestamp: new Date("2024-01-15T12:00:00Z").toISOString(),
metadata: {
agentId,
workspaceId,
grain: "daily",
timeString: day1TimeString,
},
};
await queueMemoryWrite(agentId, "daily", [day1Record]);
// Verify day summary was created
const dayRecords = getAllRecordsForGrain("daily");
expect(dayRecords.length).toBeGreaterThan(0);
expect(dayRecords[0].content).toContain("Daily Summary");
// Create summaries for days 2-7 (simulated)
for (let day = 2; day <= 7; day++) {
const dayDate = new Date(`2024-01-${14 + day}T12:00:00Z`);
const dayTimeString = formatTimeForGrain("daily", dayDate);
const dayEmbedding = await mockGenerateEmbedding(
`Daily Summary: Day ${day} activities`,
);
const dayRecord: FactRecord = {
id: `day-${dayTimeString}-summary`,
content: `Daily Summary: Day ${day} activities included project work, discussions with team members, and feature development.`,
embedding: dayEmbedding,
timestamp: dayDate.toISOString(),
metadata: {
agentId,
workspaceId,
grain: "daily",
timeString: dayTimeString,
},
};
await queueMemoryWrite(agentId, "daily", [dayRecord]);
}
// ============================================
// PHASE 3: Weekly Summarization (End of Week 2)
// ============================================
vi.setSystemTime(new Date("2024-01-22T00:00:00Z")); // Start of Week 2
// Get all daily summaries from Week 1
const week1DailySummaries = await mockQuery(agentId, "daily", {
limit: 1000,
temporalFilter: {
startDate: new Date("2024-01-15T00:00:00Z").toISOString(),
endDate: new Date("2024-01-21T23:59:59Z").toISOString(),
},
});
expect(week1DailySummaries.length).toBeGreaterThanOrEqual(7);
const week1Content = week1DailySummaries.map((r: FactRecord) => r.content);
const week1Summary = await summarizeWithLLM(
week1Content,
"weekly",
workspaceId,
agentId,
);
expect(week1Summary).toContain("Weekly Summary");
expect(week1Summary).toContain("John");
expect(week1Summary).toContain("Sarah");
const week1Embedding = await mockGenerateEmbedding(week1Summary);
const week1TimeString = formatTimeForGrain(
"weekly",
new Date("2024-01-15"),
);
const week1Record: FactRecord = {
id: `week-${week1TimeString}-summary`,
content: week1Summary,
embedding: week1Embedding,
timestamp: new Date("2024-01-18T12:00:00Z").toISOString(),
metadata: {
agentId,
workspaceId,
grain: "weekly",
timeString: week1TimeString,
},
};
await queueMemoryWrite(agentId, "weekly", [week1Record]);
// Verify weekly summary was created
const weekRecords = getAllRecordsForGrain("weekly");
expect(weekRecords.length).toBeGreaterThan(0);
expect(weekRecords[0].content).toContain("Weekly Summary");
// ============================================
// PHASE 4: Monthly Summarization (End of Month 1)
// ============================================
// Create additional weekly summaries for the month (simulated)
for (let week = 2; week <= 4; week++) {
const weekStartDate = new Date(2024, 0, 15 + (week - 1) * 7 + 1); // January, day calculation
const weekTimeString = formatTimeForGrain("weekly", weekStartDate);
const weekEmbedding = await mockGenerateEmbedding(
`Weekly Summary: Week ${week}`,
);
const weekMidDate = new Date(2024, 0, 15 + (week - 1) * 7 + 3); // Mid-week date
const weekRecord: FactRecord = {
id: `week-${weekTimeString}-summary`,
content: `Weekly Summary: Week ${week} activities included continued project development and team collaboration.`,
embedding: weekEmbedding,
timestamp: weekMidDate.toISOString(),
metadata: {
agentId,
workspaceId,
grain: "weekly",
timeString: weekTimeString,
},
};
await queueMemoryWrite(agentId, "weekly", [weekRecord]);
}
// Advance to start of Month 2
vi.setSystemTime(new Date("2024-02-01T00:00:00Z"));
// Get all weekly summaries from January
const januaryWeeklySummaries = await mockQuery(agentId, "weekly", {
limit: 1000,
temporalFilter: {
startDate: new Date("2024-01-01T00:00:00Z").toISOString(),
endDate: new Date("2024-01-31T23:59:59Z").toISOString(),
},
});
expect(januaryWeeklySummaries.length).toBeGreaterThan(0);
const monthContent = januaryWeeklySummaries.map(
(r: FactRecord) => r.content,
);
const monthSummary = await summarizeWithLLM(
monthContent,
"monthly",
workspaceId,
agentId,
);
expect(monthSummary).toContain("Monthly Summary");
const monthEmbedding = await mockGenerateEmbedding(monthSummary);
const monthTimeString = formatTimeForGrain(
"monthly",
new Date("2024-01-01"),
);
const monthRecord: FactRecord = {
id: `month-${monthTimeString}-summary`,
content: monthSummary,
embedding: monthEmbedding,
timestamp: new Date("2024-01-15T12:00:00Z").toISOString(),
metadata: {
agentId,
workspaceId,
grain: "monthly",
timeString: monthTimeString,
},
};
await queueMemoryWrite(agentId, "monthly", [monthRecord]);
// Verify monthly summary was created
const monthRecords = getAllRecordsForGrain("monthly");
expect(monthRecords.length).toBeGreaterThan(0);
expect(monthRecords[0].content).toContain("Monthly Summary");
// ============================================
// PHASE 5: Quarterly Summarization (End of Q1)
// ============================================
// Create additional monthly summaries for Q1 (simulated)
for (let month = 2; month <= 3; month++) {
const monthDate = new Date(2024, month - 1, 1); // month is 1-indexed, Date month is 0-indexed
const monthTimeString = formatTimeForGrain("monthly", monthDate);
const monthEmbedding = await mockGenerateEmbedding(
`Monthly Summary: Month ${month}`,
);
const monthMidDate = new Date(2024, month - 1, 15);
const monthRecord: FactRecord = {
id: `month-${monthTimeString}-summary`,
content: `Monthly Summary: Month ${month} activities included project milestones and team growth.`,
embedding: monthEmbedding,
timestamp: monthMidDate.toISOString(),
metadata: {
agentId,
workspaceId,
grain: "monthly",
timeString: monthTimeString,
},
};
await queueMemoryWrite(agentId, "monthly", [monthRecord]);
}
// Advance to start of Q2
vi.setSystemTime(new Date("2024-04-01T00:00:00Z"));
// Get all monthly summaries from Q1
const q1MonthlySummaries = await mockQuery(agentId, "monthly", {
limit: 1000,
temporalFilter: {
startDate: new Date("2024-01-01T00:00:00Z").toISOString(),
endDate: new Date("2024-03-31T23:59:59Z").toISOString(),
},
});
expect(q1MonthlySummaries.length).toBeGreaterThan(0);
const quarterContent = q1MonthlySummaries.map((r: FactRecord) => r.content);
const quarterSummary = await summarizeWithLLM(
quarterContent,
"quarterly",
workspaceId,
agentId,
);
expect(quarterSummary).toContain("Quarterly Summary");
const quarterEmbedding = await mockGenerateEmbedding(quarterSummary);
const quarterTimeString = formatTimeForGrain(
"quarterly",
new Date("2024-01-01"),
);
const quarterRecord: FactRecord = {
id: `quarter-${quarterTimeString}-summary`,
content: quarterSummary,
embedding: quarterEmbedding,
timestamp: new Date("2024-02-15T12:00:00Z").toISOString(),
metadata: {
agentId,
workspaceId,
grain: "quarterly",
timeString: quarterTimeString,
},
};
await queueMemoryWrite(agentId, "quarterly", [quarterRecord]);
// Verify quarterly summary was created
const quarterRecords = getAllRecordsForGrain("quarterly");
expect(quarterRecords.length).toBeGreaterThan(0);
expect(quarterRecords[0].content).toContain("Quarterly Summary");
// ============================================
// PHASE 6: Yearly Summarization (End of Year)
// ============================================
// Create additional quarterly summaries for the year (simulated)
for (let quarter = 2; quarter <= 4; quarter++) {
const quarterMonth = (quarter - 1) * 3; // 0-indexed month
const quarterDate = new Date(2024, quarterMonth, 1);
const quarterTimeString = formatTimeForGrain("quarterly", quarterDate);
const quarterEmbedding = await mockGenerateEmbedding(
`Quarterly Summary: Q${quarter}`,
);
const quarterMidDate = new Date(2024, quarterMonth + 1, 15); // Mid-quarter
const quarterRecord: FactRecord = {
id: `quarter-${quarterTimeString}-summary`,
content: `Quarterly Summary: Q${quarter} achievements and milestones.`,
embedding: quarterEmbedding,
timestamp: quarterMidDate.toISOString(),
metadata: {
agentId,
workspaceId,
grain: "quarterly",
timeString: quarterTimeString,
},
};
await queueMemoryWrite(agentId, "quarterly", [quarterRecord]);
}
// Advance to start of next year
vi.setSystemTime(new Date("2025-01-01T00:00:00Z"));
// Get all quarterly summaries from 2024
const year2024QuarterlySummaries = await mockQuery(agentId, "quarterly", {
limit: 1000,
temporalFilter: {
startDate: new Date("2024-01-01T00:00:00Z").toISOString(),
endDate: new Date("2024-12-31T23:59:59Z").toISOString(),
},
});
expect(year2024QuarterlySummaries.length).toBeGreaterThan(0);
const yearContent = year2024QuarterlySummaries.map(
(r: FactRecord) => r.content,
);
const yearSummary = await summarizeWithLLM(
yearContent,
"yearly",
workspaceId,
agentId,
);
expect(yearSummary).toContain("Yearly Summary");
const yearEmbedding = await mockGenerateEmbedding(yearSummary);
const yearTimeString = formatTimeForGrain("yearly", new Date("2024-01-01"));
const yearRecord: FactRecord = {
id: `year-${yearTimeString}-summary`,
content: yearSummary,
embedding: yearEmbedding,
timestamp: new Date("2024-06-15T12:00:00Z").toISOString(),
metadata: {
agentId,
workspaceId,
grain: "yearly",
timeString: yearTimeString,
},
};
await queueMemoryWrite(agentId, "yearly", [yearRecord]);
// Verify yearly summary was created
const yearRecords = getAllRecordsForGrain("yearly");
expect(yearRecords.length).toBeGreaterThan(0);
expect(yearRecords[0].content).toContain("Yearly Summary");
// ============================================
// PHASE 7: Memory Search Across All Grains
// ============================================
vi.setSystemTime(new Date("2024-06-15T12:00:00Z"));
// Search working memory
const workingSearchResults = await searchMemory({
agentId,
workspaceId,
grain: "working",
minimumDaysAgo: 0,
maximumDaysAgo: 180,
maxResults: 10,
});
expect(workingSearchResults.length).toBeGreaterThan(0);
expect(workingSearchResults[0].content).toBeTruthy();
expect(workingSearchResults[0].date).toMatch(/^\d{4}-\d{2}-\d{2}$/);
// Search daily summaries
const dailySearchResults = await searchMemory({
agentId,
workspaceId,
grain: "daily",
minimumDaysAgo: 0,
maximumDaysAgo: 180,
maxResults: 10,
});
expect(dailySearchResults.length).toBeGreaterThan(0);
expect(dailySearchResults[0].content).toContain("Daily Summary");