-
Notifications
You must be signed in to change notification settings - Fork 74
feat(agent-memory): Phase 6 — consolidate() #254
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jamby77
wants to merge
3
commits into
feature/agent-memory-phase5-eviction
Choose a base branch
from
feature/agent-memory-phase6-consolidate
base: feature/agent-memory-phase5-eviction
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
217 changes: 217 additions & 0 deletions
217
packages/agent-memory/src/__tests__/MemoryStore.consolidate.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,217 @@ | ||
| import { describe, it, expect, vi } from 'vitest'; | ||
| import { MemoryStore } from '../MemoryStore'; | ||
| import { fakeEmbed } from './helpers/fakeEmbed'; | ||
| import { mockClient } from './helpers/mockClient'; | ||
|
|
||
| const now = Date.now(); | ||
|
|
||
| interface HitSpec { | ||
| importance: number; | ||
| ageSeconds: number; | ||
| source?: string; | ||
| } | ||
|
|
||
| function itemHit(id: string, spec: HitSpec): [string, string[]] { | ||
| const created = now - spec.ageSeconds * 1000; | ||
| const fields: Record<string, string> = { | ||
| content: `c-${id}`, | ||
| importance: String(spec.importance), | ||
| created_at: String(created), | ||
| last_accessed_at: String(created), | ||
| access_count: '0', | ||
| }; | ||
| if (spec.source !== undefined) { | ||
| fields.source = spec.source; | ||
| } | ||
| const flat: string[] = []; | ||
| for (const [field, value] of Object.entries(fields)) { | ||
| flat.push(field, value); | ||
| } | ||
| return [`mem:mem:${id}`, flat]; | ||
| } | ||
|
|
||
| function searchReply(hits: Array<[string, string[]]>): unknown[] { | ||
| const out: unknown[] = [String(hits.length)]; | ||
| for (const [key, flat] of hits) { | ||
| out.push(key, flat); | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| function consolidatingClient(hits: Array<[string, string[]]>) { | ||
| return mockClient((command, ...args) => { | ||
| if (command === 'FT.SEARCH') { | ||
| return searchReply(hits); | ||
| } | ||
| if (command === 'DEL') { | ||
| return args.length; | ||
| } | ||
| return 'OK'; | ||
| }); | ||
| } | ||
|
|
||
| function fieldValue(call: unknown[] | undefined, field: string): string | undefined { | ||
| if (!call) { | ||
| return undefined; | ||
| } | ||
| const idx = call.indexOf(field); | ||
| return idx >= 0 ? (call[idx + 1] as string) : undefined; | ||
| } | ||
|
|
||
| describe('MemoryStore.consolidate', () => { | ||
| it('summarizes matching candidates, writes a summary, deletes sources, returns counts', async () => { | ||
| const summarize = vi.fn(async (items) => `summary of ${items.length}`); | ||
| const client = consolidatingClient([ | ||
| itemHit('a', { importance: 0.2, ageSeconds: 100000 }), | ||
| itemHit('b', { importance: 0.3, ageSeconds: 200000 }), | ||
| ]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const result = await store.consolidate({ | ||
| namespace: 'u1', | ||
| olderThanSeconds: 3600, | ||
| maxImportance: 0.5, | ||
| summarize, | ||
| }); | ||
|
|
||
| expect(summarize).toHaveBeenCalledTimes(1); | ||
| expect(summarize.mock.calls[0][0].map((i: { id: string }) => i.id)).toEqual(['a', 'b']); | ||
| expect(result.consolidated).toBe(2); | ||
| expect(result.created).toHaveLength(1); | ||
| expect(result.deleted).toBe(2); | ||
|
|
||
| const hset = client.call.mock.calls.find((c) => c[0] === 'HSET'); | ||
| expect(fieldValue(hset, 'content')).toBe('summary of 2'); | ||
| expect(fieldValue(hset, 'source')).toBe('summary'); | ||
| expect(hset?.[1]).toBe(`mem:mem:${result.created[0]}`); | ||
|
|
||
| const del = client.call.mock.calls.find((c) => c[0] === 'DEL'); | ||
| expect(del?.slice(1).sort()).toEqual(['mem:mem:a', 'mem:mem:b']); | ||
| }); | ||
|
|
||
| it('pushes olderThanSeconds into the query as a created_at upper bound', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([itemHit('a', { importance: 0.2, ageSeconds: 100000 })]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| await store.consolidate({ olderThanSeconds: 3600, summarize }); | ||
|
|
||
| const search = client.call.mock.calls.find((c) => c[0] === 'FT.SEARCH'); | ||
| const filter = search?.[2] as string; | ||
| // Server-side range so the scan limit applies to actual matches, not an | ||
| // arbitrary first window. | ||
| expect(filter).toMatch(/@created_at:\[-inf \d+\]/); | ||
| }); | ||
|
|
||
| it('pushes maxImportance into the query as an importance upper bound', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([itemHit('a', { importance: 0.2, ageSeconds: 100000 })]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| await store.consolidate({ maxImportance: 0.5, summarize }); | ||
|
|
||
| const search = client.call.mock.calls.find((c) => c[0] === 'FT.SEARCH'); | ||
| expect(search?.[2] as string).toContain('@importance:[-inf 0.5]'); | ||
| }); | ||
|
|
||
| it('excludes prior summaries from the candidate scan so a default run does not re-fold them', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([itemHit('a', { importance: 0.2, ageSeconds: 100000 })]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| await store.consolidate({ namespace: 'u1', summarize }); | ||
|
|
||
| const search = client.call.mock.calls.find((c) => c[0] === 'FT.SEARCH'); | ||
| expect(search?.[2] as string).toContain('-@source:{summary}'); | ||
| }); | ||
|
|
||
| it('writes the summary scoped to the request at summaryImportance', async () => { | ||
| const summarize = vi.fn(async () => 'merged'); | ||
| const client = consolidatingClient([itemHit('a', { importance: 0.1, ageSeconds: 100000 })]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| await store.consolidate({ namespace: 'u1', summarize, summaryImportance: 0.9 }); | ||
|
|
||
| const hset = client.call.mock.calls.find((c) => c[0] === 'HSET'); | ||
| expect(fieldValue(hset, 'importance')).toBe('0.9'); | ||
| expect(fieldValue(hset, 'namespace')).toBe('u1'); | ||
| expect(fieldValue(hset, 'source')).toBe('summary'); | ||
| }); | ||
|
|
||
| it('keeps sources when deleteSources is false', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([ | ||
| itemHit('a', { importance: 0.2, ageSeconds: 100000 }), | ||
| itemHit('b', { importance: 0.2, ageSeconds: 100000 }), | ||
| ]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const result = await store.consolidate({ | ||
| summarize, | ||
| deleteSources: false, | ||
| olderThanSeconds: 3600, | ||
| }); | ||
|
|
||
| expect(result.consolidated).toBe(2); | ||
| expect(result.created).toHaveLength(1); | ||
| expect(result.deleted).toBe(0); | ||
| expect(client.call.mock.calls.some((c) => c[0] === 'DEL')).toBe(false); | ||
| }); | ||
|
|
||
| it('returns zeros and does not summarize or write when nothing matches', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const result = await store.consolidate({ olderThanSeconds: 3600, summarize }); | ||
|
|
||
| expect(summarize).not.toHaveBeenCalled(); | ||
| expect(result).toEqual({ consolidated: 0, created: [], deleted: 0 }); | ||
| expect(client.call.mock.calls.some((c) => c[0] === 'HSET')).toBe(false); | ||
| expect(client.call.mock.calls.some((c) => c[0] === 'DEL')).toBe(false); | ||
| }); | ||
|
|
||
| it('throws when given no scope, tags, or selection criteria (prevents whole-store consolidation)', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const store = new MemoryStore({ client: mockClient(), name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| await expect(store.consolidate({ summarize })).rejects.toThrow(/scope|criteria/i); | ||
| expect(summarize).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('defaults summaryImportance to 0.7 and deletes sources by default', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([itemHit('a', { importance: 0.2, ageSeconds: 100000 })]); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const result = await store.consolidate({ summarize, olderThanSeconds: 3600 }); | ||
|
|
||
| const hset = client.call.mock.calls.find((c) => c[0] === 'HSET'); | ||
| expect(fieldValue(hset, 'importance')).toBe('0.7'); | ||
| expect(result.deleted).toBe(1); | ||
| }); | ||
|
|
||
| it('writes the summary without a capacity pass so it cannot be evicted then orphaned', async () => { | ||
| const summarize = vi.fn(async () => 'summary'); | ||
| const client = consolidatingClient([ | ||
| itemHit('a', { importance: 0.2, ageSeconds: 100000 }), | ||
| itemHit('b', { importance: 0.2, ageSeconds: 100000 }), | ||
| ]); | ||
| const store = new MemoryStore({ | ||
| client, | ||
| name: 'mem', | ||
| embedFn: fakeEmbed(8), | ||
| maxItemsPerScope: 1, | ||
| }); | ||
|
|
||
| const result = await store.consolidate({ namespace: 'u1', summarize }); | ||
|
|
||
| expect(result.created).toHaveLength(1); | ||
| expect(client.call.mock.calls.some((c) => c[0] === 'HSET')).toBe(true); | ||
| // Exactly one FT.SEARCH (the candidate scan): the summary write triggers no | ||
| // capacity probe/scan, so enforceCapacity can't evict the just-written summary | ||
| // while the sources still inflate the count. | ||
| const searches = client.call.mock.calls.filter((c) => c[0] === 'FT.SEARCH'); | ||
| expect(searches).toHaveLength(1); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.